Python learns _11_ classes and instances

Source: Internet
Author: User
Tags ming uppercase letter

Classes and instances

A class is a template for an object to create an instance, whereas an instance is an entity of an object. Class is defined using the Class keyword:

Class MyClass:
? ? Pass

Creating instances in Python uses the factory function directly (with the class name plus a pair of parentheses) and differs from other languages using the New keyword:

My_obj = MyClass ()

In general, the class name begins with an uppercase letter, and the object name begins with a lowercase letter or an underscore.

When an object is instantiated, it executes the __init__ () method in the class definition, which executes various initialization operations that contain the instance.

Methods and functions are different: methods are called by the object, in the method definition, the first argument must be the display of self, the current object, and the function does not pass in the current object self, you can say the method is a special function, he specified the calling object, and can get the properties of the calling object. Both functions and methods are instances of the function class:

Class MyClass (object):
? ? def __init__ (self):
? ? ? ? Pass
? ? Def method1 (A, B):
? ? ? ? Print (A+B)
? ? def method2 (self,a,b):
? ? ? ? Print (A+B)
obj = MyClass ()
Myclass.method1 (ON)
OBJ.METHOD2 (ON)
Print (Type (MYCLASS.METHOD1))
Print (Type (MYCLASS.METHOD2))

In the above code, Obj.method2 is the method, and myclass.method1 is a normal function, why use MYCLASS.METHOD1 is because the Method1 namespace is included in MyClass, and the reason for using OBJ.METHOD2 is because Method2 is an obj A method in the class, and obj as the object of the METHOD1 call.

From the above code can also delay the following conclusions:

1. MYCLASS.METHOD2 will produce an error: TYPEERROR:METHOD2 () takes exactly 3 arguments (2 given). While MyClass is also an object, when executing myclass.method2 (), it is not possible to use MyClass as the current object represented by self, because the instance's method must exist in the class, and the instance's properties exist in the instance itself. MyClass call Method2 is unsuccessful because the MyClass class: type does not have the method, so Myclass.method2 () is just a function in the MyClass namespace, and the function requires an object to be passed in. So it caused a typeerror error.

2. OBJ.METHOD1 will produce an error: TYPEERROR:METHOD1 () takes exactly 2 positional arguments (3 given). Although the call error, but the reason for the error is only because the number of parameters mismatch, thus, an object call method, the method must be explicit the first object is self. Also, when obj is called, the MyClass namespace is not used, because obj is an instance of MyClass and will integrate the MyClass namespace.

Properties of the Object

In Python, an instance can add an object at any moment, even if the property is not defined in the class, but the statement does not have any errors, and it can be called later, which may be very convenient, but it also hides a lot of drawbacks and is prone to passing unnecessary attributes on known objects. To make a mess:

Class MyClass:
? ? def __init__ (self,a,b):
? ? ? ? SELF.A = A
? ? ? ? SELF.B = b
obj = MyClass
Print (OBJ.A)
OBJ.A = 3
Print (OBJ.A)
def a_method (self,c):
? ? SELF.C = C
From types Import Methodtype
Obj.a_method = Methodtype (a_method,obj)
Obj.a_method (4)
Print (OBJ.C)

The above-mentioned methods and properties beyond the class definition are not available in other homogeneous objects, and can be seen as a technique similar to one in Ruby, and the method added to obj through the above code actually exists in the single-piece class of obj.

You can restrict the properties of a class by __slots__ to prevent unnecessary variables from being added to the instance:

Class MyClass:
? ? __slots___ = (' A ', ' B ')
? ? ...

At this point, if you add additional properties to obj, you will be notified of errors in the MyClass that do not have the property, thereby limiting the properties of the object.

An object's properties are no longer arbitrarily added, but can still be easily accessed externally by external code, by adding two underscores before the variable to represent a private variable:

Class Student:
? ? __slots__ = (' score ', ' Grade ')
? ? def __init__ (Self,score):
? ? ? ? Self.score = Score
? ? def getscore (self):
? ? ? ? If Self.score >= 90:
??????? self.grade = ' A '
? ? ? ? Elif Self.score >= 60:
? ? ? ? ? ? Self.grade = ' B '
? ? ? ? Elif Self.score < 60:
? ? ? ? ? ? Self.grade = ' C '
? ? ? ? Return Self.grade
Xiaoming = Student (47)
Xiaoming.score = 90
Print (Xiaoming.getscore ())

In the above code, although in the initialization of Xiao Ming's score when the input of 47 points, but still can be in the outside to modify the results, because Xiao Ming understand a little python, an instant from the poor into a top student, the result is not want to be seen. After changing score to __score:

Class Student:
? ? __slots__ = (' __score ', ' Grade ')
? ? def __init__ (Self,score):
? ? ? ? Self.__score = Score
? ? def getgrade (self):
? ? ? ? If Self.__score >= 90:
? ? ? ? ? ? Self.grade = ' A '
? ? ? ? Elif Self.__score >= 60:
? ? ? ? ? ? Self.grade = ' B '
? ? ? ? Elif Self.__score < 60:
? ? ? ? ? ? Self.grade = ' C '
? ? ? ? Return Self.grade

At this time, Xiao Ming's opportunistic modification of his score means no longer effective. When you access Xiaoming.__score, the following error occurs: attributeerror: ' Student ' object has no attribute ' __score '

Still, Xiao Ming can still do this:

Xiaoming._student__score = 100

Because when using double underscores, Python simply adds the _classname prefix before the name of the variable to avoid being directly accessed (different versions of the interpreter will vary) rather than being truly inaccessible, and Python does not have a really non-operational mechanism, and is similar to _ Student the variable names that start with these single underscores, although they can be accessed externally, it is best not to do so, and the single underline means that although I am not a private variable, please take me as a private variable, which may be a compromise to python without a private variable.

At this time, I also have no way to deal with the small clear. This is a very interesting story, in Ruby, any instance variable can not be accessed externally until the set method and get method are provisioned, and the variable is really a property only by setting the setter method or getter method to the private variable. All in all, for instance variables to become attributes to do some necessary work. In Python, it's almost impossible to prevent an object from accessing a variable defined in a class, and even if you don't have to __slots__ to prevent the addition of various properties into the object, the work we're going to do instead becomes a way of trying to make the property inaccessible.

Use real properties

Python can also, like other languages, implement getter, setter methods to access and set properties through the @property decorator, so that you can "deceiving" to say that you cannot set this property:

Class Student:
? ? __slots__ = (' _score ', ' _grade ')
? ? def __init__ (Self,score):
? ? ? ? Self._score = Score
? ? @property
? ? DEF score (self):
? ? ? ? Return _score
? ? @property
? ? def grade (self):
? ? ? ? If Self._score >= 90:
? ? ? ? ? ? Self._grade = ' A '
? ? ? ? Elif Self._score >= 60:
? ? ? ? ? ? Self._grade = ' B '
? ? ? ? Elif Self._score < 60:
? ? ? ? ? ? Self._grade = ' C '
? ? ? ? Return Self._grade

When the @property decorator is used, the Getter method is implemented so that the external can be seen, and if you want to set the Getter method, add:

? ? @score. Setter
? ? DEF score (Self,value):
? ? ? ? Score._score = value

Like other languages, the method name is the attribute name, Xiao Ming can see his grades through Xiaoming.score, when there is no setter method defined, Xiaoming can not be xiaoming.score to modify their results, but this does not mean that Xiao Ming really can not change it? In fact, through the above code can be seen, python internal variable name is not score, but _score, this is why I said "deceiving" reason, xiaoming can still through the Xiaoming._score to modify their results. In short, Python does not really prevent an object from accessing the variables in the class definition, which is a bit distressing.

Today is an incomplete day.

Python learns _11_ classes and instances

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.