问题
Just a simple question : when should I use the term 'class', and when should I use the term 'type' in Python ?
- is 'class' only for user-defined types, and 'type' for built-in types ?
- or now that everything is a type ... should I use always 'type' even for user-defined classes ?
- ... ?
回答1:
It is more or less historical: they used to be different a long time ago, which has no practical implications anymore.
Edit: I use "class
" when referring to concrete implementations and "type
" in a more informal way, when speaking about high level data structures, application arcitecture etc. In my thinking a type is a more general thing, I don't think of every class as a distinct type.
Also, when I use metaclasses (very rarely) I speak of types.
回答2:
A class is a Python data structure that can be used as a template for instances of that class by calling it, e.g. foo = Foo()
.
A type is a class that can be used as a template for additional classes by way of inheritance, e.g. class Foo(Bar):
Since Python supports inheritance, all classes can be used as templates for additional classes, which means that all classes are in fact types.
This is especially true since the advent of "new-style classes," derived from object
, which unify the type hierarchy of user-defined classes with the built-in types. Classes were always types, but now they are the same kind of types as the built-in types.
Although Python classes are types, I still find the distinction a useful one, so the terms are not entirely synonyms in my mind.
Bonus definition: a metaclass is a class whose instances are classes. In Python, these must be derived from the type
class, just as new-style objects are derived from object.
回答3:
I use "type" to refer to the general case, but I switch to "class" when I'm speaking about attributes.
But it really doesn't matter which you choose.
{}
is of typedict
. Theiteritems()
method of thedict
class returns an iterator.
回答4:
You could say that an object at run-time is of a certain single type, but by means of (multiple) inheritance it can be viewed as belonging to several classes.
回答5:
This might not answer your question directly, but it might give you a sense of the difference between type and class.
class Card:
def __init__(self, suit=0, rank=0):
self.suit = suit
self.rank = rank
card1 = Card()
Card
is a class object, so its type is type
.
However, card1
is an instance of Card
, so its type is Card
.
来源:https://stackoverflow.com/questions/4162578/python-terminology-class-vs-type