Python basics-Class variables and instance variables

Source: Internet
Author: User

Python basics-Class variables and instance variables

Write in front

If not specifically stated, the following are based on Python3

Outline:

1. Class variables and instance variables

This is described in Python tutorial for class variables and instance variables:

Generally speaking, instance variables is for data unique to each instance and class variables is for attributes and met Hods shared by all instances of the class:

Typically, instance variables are data that is unique to each instance, and class variables are properties and methods shared by all instances of the class.

In fact, I prefer to use class attributes and instance properties to address them, but the word variable has become the customary appellation of the programming language. A normal example is:

Class Dog:    kind = ' Canine '         # class variable shared by all Instancesdef __init__ (self, name): Self.name = name    # Instance variable unique to each instance

Class Dog , the Class property kind is shared for all instances, and instance properties name are Dog unique for each instance.

2. class objects and instance objects

Class 2.1 Objects

PythonEverything in the object; When the class definition is complete, a name that points to the class object is defined in the current scope with the class name. Such as

Class Dog:pass

The name is defined in the current scope Dog , pointing to the class object Dog .

the operations supported by the class object :
In general, class objects only support two operations:

    1. Instantiate instance_name = class_name() , instantiate, instantiate, create an instance of the class.

    2. Property Reference, class_name.attr_name and the way in which the Class property is referenced.

2.2 Instance Object

Instance objects are artifacts of class object instantiation, and instance objects support only one operation:

    1. The property reference is the same as the Class object property reference, using the same way instance_name.attr_name .

According to strict object-oriented thinking, all attributes should be instances, and class attributes should not exist. In Python this case, because the class attribute binding should not exist, only the function definition is left in the class definition.

In Python tutorial about class definitions also say:

In practice, the statements inside a class definition would usually be function definitions, and other statements is allow Ed, and sometimes useful.

In practice, a statement in a class definition is usually a function definition, but other statements are allowed and sometimes useful.

The other statements mentioned here refer to the binding statements of the class properties.

3. Property Binding

When defining a class, we usually say that the definition attribute is actually divided into two aspects:

    1. Class Property Binding

    2. Instance Property bindings

The word binding is more precise, whether it is a class object or an instance object, and the property is based on the object.

We're talking about property bindings, which first require a mutable object to perform the bind operation, using the

Objname.attr = Attr_value

The way to bind properties for an object objname attr .

There are two situations:

    1. If attr the property already exists, the bind operation points the property name to the new object;

    2. If it does not exist, a new attribute is added to the object, which you can then refer to the new property.

Class 3.1 Property Binding

PythonAs a dynamic language, both class and instance objects can bind arbitrary properties at run time. Therefore, the binding of a class attribute occurs in two places:

    1. class is defined;

    2. Run at any stage.

The following example illustrates the period in which a class attribute binding occurs:

Class Dog:    kind = ' canine ' dog.country = ' China ' Print (dog.kind, '-', dog.country) # output:canine  -  Chinadel Dog.kindprint (Dog.kind, '-', dog.country) # Attributeerror:type object ' Dog ' has no attribute ' kind '

In a class definition, the binding of a class property is not used objname.attr = attr_value , which is a special case, in fact, the same way that the class name binding property is used later.
Because it is a dynamic language, you can add properties at run time and delete properties.

3.2 Instance Property bindings

As with class property bindings, instance property bindings also occur in two places:

    1. class is defined;

    2. Run at any stage.

Example:

Class Dog:def __init__ (self, Name, age): Self.name = Nameself.age = Agedog = Dog (' Lily ', 3) Dog.fur_color = ' Red ' Print ('%s i S%s years old, it has%s fur '% (dog.name, dog.age, Dog.fur_color)) # output:lily was 3 years old, it had red fur

Pythonclass instances have two special properties:

    1. __init__Executes when instantiated

    2. PythonWhen an instance invokes a method, the instance object is passed as the first argument

So, __init__ the method is the self instance object itself, here is dog the statement

Self.name = Nameself.age = Age

and the following statements

Dog.fur_color = ' Red '

dogadd three properties to an instance name , age fur_color .

4. Attribute references

The reference to the property is different from the direct access name and does not involve scopes.

Class 4.1 Property Reference

A reference to a class property is definitely required for a class object, and the attributes are divided into two types:

    1. Data properties

    2. function properties

Data property references are simple, examples:

Class Dog:    kind = ' canine ' dog.country = ' China ' Print (dog.kind, '-', dog.country) # output:canine  -  China

There are typically few requirements for referencing class function properties, as an example:

Class Dog:    kind = ' canine ' def tell_kind ():p rint (dog.kind)        dog.tell_kind () # Output:canine

The function tell_kind in the reference kind needs to be used Dog.kind instead of directly kind , involving scopes, which is described in another article in my: Python advanced-namespaces and scopes

4.2 Instance Property Reference

Using instance object reference properties is a little more complicated because instance objects can reference class properties and instance properties. However, the instance object references properties when the following rules are followed:

    1. Always find the attribute in the instance object first, and then find the attribute in the Class property;

    2. The property binding statement always creates a new property for the instance object, and when the property exists, updates the object that the property points to.

4.2.1 Data Property Reference

Example 1:

Class Dog:    kind = ' canine ' country = ' China ' def __init__ (self, name, age, country): Self.name = Nameself.age = AGESELF.C Ountry = Countrydog = Dog (' Lily ', 3, ' Britain ') print (Dog.name, Dog.age, Dog.kind, Dog.country) # output:lily 3 Canine Brit Ain

Both the class object Dog and the instance object dog have properties, which, country according to the rules, dog.country refer to the properties of the instance object, but the instance object dog has no attributes kind and the properties of the class object are referenced by the rule.

Example 2:

Class Dog:    kind = ' canine ' country = ' China ' def __init__ (self, name, age, country): Self.name = Nameself.age = AGESELF.C Ountry = Countrydog = Dog (' Lily ', 3, ' Britain ') print (Dog.name, Dog.age, Dog.kind, Dog.country) # Lily 3 Canine Britainprin T (dog.__dict__) # {' Name ': ' Lily ', ' Age ': 3, ' country ': ' Britain '}dog.kind = ' feline ' Print (Dog.name, dog.age, Dog.kind, do G.country) # Lily 3 Feline Britainprint (dog.__dict__) print (dog.kind) # Canine No change to the class attribute of the pointing # {' name ': ' Lily ', ' Age ': 3, ' cou Ntry ': ' Britain ', ' kind ': ' Feline '}

Using a property binding statement, the property dog.kind = 'feline' is added to the instance object by rule, followed by a dog kind dog.kind property that references the instance object.

This is not to be thought of as changing the point of a class property, but rather Dog.kind as a new attribute for an instance object, you can __dict__ prove it using the way you view it.

Example 3, a mutable class Property reference:

Class Dog:        tricks = []def __init__ (Self, name): Self.name = Namedef 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 is self.tricks.append(trick) not a property-bound statement, so the Mutable object is modified on the Class property.

4.2.2 Method Property Reference

Unlike data members, a class function property becomes a method property in an instance object.

Let's look at an example:

Class Methodtest:def inner_test (self):p rint ("in class") def outer_test ():p rint (' Out of class ') MT = Methodtest () mt.outer _test = Outer_testprint (Type (methodtest.inner_test))  # <class ' function ' >print (type (mt.inner_test)          ) #<class ' method ' >print (Type (mt.outer_test))          #<class ' function ' >

As you can see, the Class function property becomes a method property in the instance object, but not all functions in the instance object are methods.

This method object is described in Python Tutorial:

When an instance attribute was referenced that isn ' t a data attribute, it class is searched. If the name denotes a valid class attribute a function object, a method object is created by packing (pointers to) The instance object and the function object just found together in a abstract Object:this is the method object. When the method object was called with an argument list, a new argument list was constructed from the instance object and th e argument list, and the function object is called with this new argument list.

When you reference an instance property of a non-data property, it searches for its corresponding class. If the name is a valid function object, Python packages the instance object together with the function object into an abstract object and creates a method object from that object: This is the called method object. When you invoke a method object using the parameter list, a new parameter list is built using the instance object and the original parameter list, and the function object is invoked with the new parameter list.

Then, the instance object will only pass itself as the first argument when it refers to the method property, not the normal function of the instance object.
So you can call methods and functions directly using the following methods:

Mt.inner_test () mt.outer_test ()

Except for the difference between a method and a function, its reference is the same as the Data property

5. Best practices

Although Python acts as a dynamic language, it supports binding properties at run time, but from an object-oriented point of view, the properties are determined when the class is defined.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.