Python base - instance variables and class variables
EDITORIAL
The non-specifically stated hereinafter are based Python3
Outline:
1. The instance variables and class variables
In Python Tutorial in for instance variables and class variables are described:
Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:
In general, instance variables unique to each instance of data, class variables and class methods and properties shared by all instances.
In fact, I prefer to use the class and instance properties to call them, but variable word has become accustomed to the title programming language. A normal sample is:
class Dog:
kind = 'canine' # class variable shared by all instances def __init__(self, name): self.name = name # instance variable unique to each instance
Class Dog
, the class attribute kind
is shared by all instances; attributes instance name
for each Dog
unique instance.
2. The class object and instance objects
2.1 class object
Python
Everything in the object; after the class definition is complete, with a class called name in the current definition of scope, pointing to the name of the class object. Such as
class Dog:
pass
It will be defined in the current scope name Dog
, point to the class object Dog
.
Class objects support operations :
In general, the class object supports only two operations:
- Instantiating; used
instance_name = class_name()
way of example, create an instance of the class instantiation operation. - Attribute references; use
class_name.attr_name
mode reference properties.
2.2 instance object
Examples of the object is a class object instantiated product, supports only one instance of an object operations:
- Attribute references; the same property class object reference to the embodiment, using
instance_name.attr_name
FIG.
In accordance with strict object-oriented thinking, all attributes should be instances of the class attribute should not exist. Then Python
, due to the binding properties of the class should not exist, the class definition will only function is defined.
In Python tutorial about the class definition also say:
In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful.
In practice, the class definition statements usually function definitions, but other statements are also allowed, and sometimes useful.
Here that the other statements, the statement refers to the binding properties of the class.
3. Binding Properties
When you define a class, we usually say that the definition of property, in fact, is divided into two areas:
- Class attribute binding
- Examples of binding properties
With the binding of the word is more precise; whether it is a class object or instance of an object, the object attributes are relying exist.
We say that the properties of the binding, you first need a variable object, to perform the binding operation,
objname.attr = attr_value
Way, the object objname
binding properties attr
.
These two cases:
- If the property
attr
already exists, the binding properties will point to the new name of the object; - If not, the object was to add new properties, new properties can be referenced later.
3.1 class attribute binding
Python
As a dynamic language, objects and class instance object can bind any property at runtime. Therefore, the binding class property occurs in two places:
- When the class is defined;
- Any stage of the operation.
The following example illustrates the binding occurs during the class attribute:
class Dog:
kind = 'canine'
Dog.country = 'China' print(Dog.kind, ' - ', Dog.country) # output: canine - China del Dog.kind print(Dog.kind, ' - ', Dog.country) # AttributeError: type object 'Dog' has no attribute 'kind'
In the class definition, the class attribute does not bind the use objname.attr = attr_value
mode, which is a special case, in fact, it is equivalent to the embodiment later using the class name of the binding properties.
Because it is a dynamic language, it is possible to increase the property at run time, remove the property.
3.2 Examples of binding properties
Binding properties of the same class, instance binding property also occur in two places:
- When the class is defined;
- Any stage of the operation.
Example:
class Dog:
def __init__(self, name, age): self.name = name self.age = age dog = Dog('Lily', 3) dog.fur_color = 'red' print('%s is %s years old, it has %s fur' % (dog.name, dog.age, dog.fur_color)) # Output: Lily is 3 years old, it has red fur
Python
Class instance has two special features:
__init__
Performed at instantiationPython
Call instance methods, instance objects will pass as the first parameter
Therefore, the __init__
method self
is an instance of the object itself, here is dog
the statement
self.name = name
self.age = age
And the following statement
dog.fur_color = 'red'
Examples of dog
the addition of three attributes name
, age
, fur_color
.
4. attribute references
Reference to the property with direct access to a different name, is not related to the scope.
4.1 class attribute references
Reference properties is certainly required class objects, properties, divided into two types:
- Property data
- Function Properties
Data attribute reference is very simple example:
class Dog:
kind = 'canine'
Dog.country = 'China' print(Dog.kind, ' - ', Dog.country) # output: canine - China
Usually there is little reference to the needs of the properties class functions, example:
class Dog:
kind = 'canine'
def tell_kind(): print(Dog.kind) Dog.tell_kind() # Output: canine
Function tell_kind
in reference to kind
need Dog.kind
rather than directly kind
, related to the scope, which is described in another post my article: Python Advanced - namespace scopes
4.2 instance attribute is referenced
Example object reference attribute is slightly more complicated, because the instance object can reference properties and attributes instances. However, the following rules when referencing instance object attributes:
- First instance object always find property, and then look for the class attribute properties;
- Attribute binding statement always create new properties for the object instance, when the property exists, it pointed to update the object properties.
4.2.1 Data attribute reference
Example 1:
class Dog:
kind = 'canine'
country = 'China' def __init__(self, name, age, country): self.name = name self.age = age self.country = country dog = Dog('Lily', 3, 'Britain') print(dog.name, dog.age, dog.kind, dog.country) # output: Lily 3 canine Britain
Class object Dog
and instance objects dog
have attributes country
, according to the rules, dog.country
will refer to an object property instance; however, an instance object dog
without attribute kind
references property class object in accordance with rules.
Example 2:
class Dog:
kind = 'canine'
country = 'China' def __init__(self, name, age, country): self.name = name self.age = age self.country = country dog = Dog('Lily', 3, 'Britain') print(dog.name, dog.age, dog.kind, dog.country) # Lily 3 canine Britain print(dog.__dict__) # {'name': 'Lily', 'age': 3, 'country': 'Britain'} dog.kind = 'feline' print(dog.name, dog.age, dog.kind, dog.country) # Lily 3 feline Britain print(dog.__dict__) print(Dog.kind) # canine 没有改变类属性的指向 # {'name': 'Lily', 'age': 3, 'country': 'Britain', 'kind': 'feline'}
Use attribute binding statement dog.kind = 'feline'
, according to the rules, it is an example of an object dog
increased property kind
, use the back of dog.kind
a reference to an instance of an object's properties.
Do not think this will change the class attribute Dog.kind
points to is actually a new property to an object instance, can be used to view __dict__
a way to prove it.
Example 3, the variable class attribute references:
class Dog:
tricks = []
def __init__(self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick) d = Dog('Fido') e = Dog('Buddy') d.add_trick('roll over') e.add_trick('play dead') print(d.tricks) # ['roll over', 'play dead']
The statement self.tricks.append(trick)
is not binding property statement, so to modify or variable objects on the class attribute.
4.2.2 Method property references
Members of different data class instance object property functions will become Method properties.
Look at an example:
class MethodTest:
def inner_test(self): print('in class') def outer_test(): print('out of class') mt = MethodTest() mt.outer_test = outer_test print(type(MethodTest.inner_test)) # <class 'function'> print(type(mt.inner_test)) #<class 'method'> print(type(mt.outer_test)) #<class 'function'>
Can be seen, function attribute class properties into a process instance of an object, the object instance but not all functions are methods.
Python tutorial in this description method of the object:
When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.
Examples of non-referencing attribute data attributes, it will search for the corresponding class. If the name is a valid function object, Python will function object instance of the object along with packaged into an abstract object and create a method of the object based on the object: this is the method object is called. When using the method object is called the parameter list, use the instance object and the original argument list to build a new list of parameters, and use the new argument list calling function object.
Well, only in reference to the object instance attribute method, will itself as the first parameter; calling a normal function instance of an object, it will not.
You can be called directly by using a function in the following manner:
mt.inner_test()
mt.outer_test()
In addition to a function of the difference method, with reference to which data attributes are the same
5. Best Practices
Although Python
as a dynamic language runtime support binding properties, but from the perspective of object-oriented, or in the class definition, the attribute determined.