PYTHON_016 (Object-oriented properties and class methods)

Source: Internet
Author: User

I. Characteristics (PROPERTY,SETTER,DELETER)

1. Attribute: A method is disguised as a property, there is no intrinsic elevation at the code level, but looks more reasonable;

class Person :     def __init__ (self, height, weight):         = height        = weight    def  BMI (self):        return'  . 2f'= person (1.72, $)print(P.bmi ())       # Here the BMI is calculated, so it is more like a noun and should not be called as a method;

So we're going to change the way BMI is encapsulated as a property;

class Person :     def __init__ (self, height, weight):         = height        = weight    @property    def  BMI (self):        return  '. 2f'= person (1.72, +)print(P.BMI)

#property是一种特殊的属性, access to it will perform a function and then return, try to be able to directly return the value of the calculation itself, it is necessary to turn it into a property method more reasonable;

Similar to the area and circumference of the circle;

2.setter can modify the value of the property, but only one value can be passed, deleter the value of the property;

classPerson :def __init__(self,name,age): Self.name=name self.__age= AgeifType (age) isIntElse 'you entered the wrong'@propertydefAge (self):returnSelf.__age@age. SetterdefAge (self,r): Self.__age= RifType (R) isIntElse 'you entered the wrong'@age. DeleterdefAge (self):delSelf.__ageP= Person ('Bowen Liu', 5)Print(p.age) p.age= 6#executes the setter statement, modifies the property value of the method, only passes in one parameterPrint(p.age)delP.age#execute the deleter statement to delete the value in the method

Two. Class methods

1. Two preceding contents: A: Do not call the method directly with the class name, because it must be passed to self,

#class MethodclassA:defFunc (self):#Common Methods        Print(self) @classmethod#class Method    deffunc1 (CLS):Print(CLS) A1= A ()#an object can be instantiated by instantiating it,A1.func ()#The value is not passed here, and the object itself is passed by default;A.func (11)#to invoke a method with a class, pass in a value to self;

Here's the class method, called by the class name method, above the addition of an adorner @classmethod the following method is the class method;

# a1 = A () # The a1.func1 ()  # Object calls the class method, and the CLS gets the class itself.

The first parameter in the class method Cls,python the class name (class space) to the CLS automatically, regardless of who invokes the class method, the CLS refers to the class itself;

A: Application Scenarios for class methods:

1). There are methods in the class that do not require object participation

class A:     ' Alex ' = 1    @classmethod    def func1 (CLS): # This method requires no object involvement                 return cls.name + str (cls.count + 1)print(A.FUNC1 ())

2) If you use return A.name + str (a.count + 1) without the CLS, if you change the name of the class, then the bottom will have to change;

Therefore, the class method is used to change the static variables in the class.

3) In the inheritance, the parent class obtains the subclass class space;

#前面说我们父类调用和查找不到子类的空间, but through the class method, the parent class can also get the subclass space and do whatever it pleases;

class A:     =    @classmethod    def func1 (CLS):  #  Here The CLS is passed in caller B, and the parent class gets the space of the subclass;        Print (CLS)         # all of the contents of Class B can be modified.        Print (cls.age)         # return cls.name + str (cls.count + 1) class B (A):     =b.func1 ()

#如果没有类方法, you can also get all the subcategories of things

class A:     =    def  Func2 (self):        The object of theprint(self)  # Self subclass, which can get any value of the subclass space  class  B (A):    = == B () b1.func2 ()

Here with self can also get sub-categories of things, but can only check, can not change;

4) static method:

classA: @staticmethoddefLogin (username, password):ifUsername = ='Alex'  andPassword = = 123:            Print('Login Successful')        Else:            Print('Login Failed ...') A.login ('Alex', 1234)
defLogin (Username,password):ifUsername = ='Alex' andPassword = = 123: Print('Login Successful') Else: Print('Login Failed ...') Login ('Alex', 1234)

These two pieces of code do the same thing, although you can do it with a function, but that's not appropriate;

So the advantage of the class method is 1. code block, clear 2. Improve the reusability of code;

PYTHON_016 (Object-oriented properties and class methods)

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.