Sixth week - on chapter -Python3.5- instance variables and class variables

Python base - instance variables and class variables

EDITORIAL

The non-specifically stated hereinafter are based Python3

Outline:

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 kindis shared by all instances; attributes instance namefor each Dogunique instance.

2. The class object and instance objects

2.1 class object

PythonEverything 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:

  1. Instantiating; used instance_name = class_name()way of example, create an instance of the class instantiation operation.
  2. Attribute references; use class_name.attr_namemode reference properties.
2.2 instance object

Examples of the object is a class object instantiated product, supports only one instance of an object operations:

  1. Attribute references; the same property class object reference to the embodiment, using instance_name.attr_nameFIG.

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:

  1. Class attribute binding
  2. 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 objnamebinding properties attr.

These two cases:

  1. If the property attralready exists, the binding properties will point to the new name of the object;
  2. If not, the object was to add new properties, new properties can be referenced later.
3.1 class attribute binding

PythonAs a dynamic language, objects and class instance object can bind any property at runtime. Therefore, the binding class property occurs in two places:

  1. When the class is defined;
  2. 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_valuemode, 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:

  1. When the class is defined;
  2. 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

PythonClass instance has two special features:

  1. __init__Performed at instantiation
  2. PythonCall instance methods, instance objects will pass as the first parameter

Therefore, the __init__method selfis an instance of the object itself, here is dogthe statement

self.name = name
self.age = age

And the following statement

dog.fur_color = 'red'

Examples of dogthe addition of three attributes nameagefur_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:

  1. Property data
  2. 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_kindin reference to kindneed Dog.kindrather 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:

  1. First instance object always find property, and then look for the class attribute properties;
  2. 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 Dogand instance objects doghave attributes country, according to the rules, dog.countrywill refer to an object property instance; however, an instance object dogwithout attribute kindreferences 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 dogincreased property kind, use the back of dog.kinda reference to an instance of an object's properties.

Do not think this will change the class attribute Dog.kindpoints 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 Pythonas a dynamic language runtime support binding properties, but from the perspective of object-oriented, or in the class definition, the attribute determined.

Guess you like

Origin www.cnblogs.com/pcjbk/p/11068074.html