The concept of classes in Python

Source: Internet
Author: User

In Python, all data types can be treated as objects, or you can customize objects. The custom object is the concept of class-oriented objects.

 1  class   Student (object):  2  3  def  __init__   (self, name, score):  4  self.name = name  5  self.score = score  6  7  def   Print_score (self): Span>8  print  ( '  

Note: The first parameter of the __init__ method is always self, which represents the created instance itself.

So within the __init__ method, it is possible to bind various properties to self, because it points to the created instance itself.

If you want the internal properties to be inaccessible externally, you can add two underscores to the name of the property.

In Python, the variable name of an instance begins with __, and becomes a private variable (private) that can only be accessed internally and cannot be accessed externally.

So, let's change the Student class:

1 class Student (object): 2 3     def __init__ (self, Name, score):4         self.__name = name5         self.__ Score = Score67    def print_score (self):8         print ('% S:%s '% (Self.__name, Self.__score))

After the change, there is no change to the external code, but the instance variable cannot be accessed externally. __name and instance variables. __score:

1 >>> bart = Student (' Bart Simpson ', 98)2 >>> bart.__name3  Traceback (most recent):4in    <module>5 attributeerror: ' Student ' object has no attribute ' __name '

Because Python is a dynamic language, an instance created from a class can be arbitrarily bound to a property. The way to bind properties to an instance is through an instance variable, or through the self variable:

1 class Student (object): 2     def __init__ (self, name):3         self.name = name45 s = Student (' Bob ' )6 s.score = 90
1 //@property How to use2 class Student (object):3 4 def get_score (self):5          returnSelf._score6 7 def set_score (self, value):8         ifNot Isinstance (value,int):9Raise ValueError (' score must is an integer! ')Ten         ifValue < 0 or value > 100: OneRaise ValueError (' score must between 0 ~ 100! ')) ASelf._score = value

Now, to operate on any of the student instances, you cannot set score as you wish:

1 >>> s = Student ()2#  ok! 3 >>> s.get_score ()4 5 >>> s.set_score (9999)6  Traceback (most recent):7   ... 8 Valueerror:score must between 0 ~ 100!

Changes after use:

1 classStudent (object):2 @property3     defscore (self):4         returnSelf._score5 6 @score. Setter7     defscore (self, value):8         if  notisinstance (value, int):9             RaiseValueError ('score must is an integer!')Ten         ifValue < 0orValue > 100: One             RaiseValueError ('score must between 0 ~ 100!') ASelf._score = value

The implementation of @property is more complex, we first examine how to use.

To turn a getter method into a property, just add @property to it. At this point the @property itself creates another adorner @score.setter, which is responsible for turning a setter method into a property assignment.

Thus, we have a controllable property operation:

1 >>> s = Student ()2#  OK, actual conversion to S.set_score (3)  OK, actual conversion to S.get_score ()4 5 >>> s.score = 99996Traceback ( Most recent call last):7   ... 8 Valueerror:score must between 0 ~ 100!

Noticing this magical @property, when we operate on instance properties, we know that this property is probably not directly exposed, but is implemented through getter and setter methods.

The concept of classes in Python

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.