One. Properties
The so-called attribute is to disguise a method in a class as a property. At the level of the code there is no intrinsic elevation. But make the code look better.
classPerson :def __init__(self,name,age): Self.name=nameifType (age) isint:self.__age= AgeElse: Print('you entered the wrong type of age, please enter a number') @property#view of the property. Use of adorners defAge (self):returnSelf.__age@age. Setter#Modification of Properties defAge (SELF,A1):" "judge that the age you modify must be a number" " ifType (A1) isint:self.__age=A1Else: Print('you entered the wrong type of age, please enter a number') @age. Deleter#Deletion of Properties defAge (self):delSelf.__ageP1= Person ('Handsome', 20)Print(p1.age) p1.age= #看上去更像是对某一个属性进行操作Print(p1.age)delP1.agePrint(P1.__dict__)
Two. Class methods
Class method: A method called by a class name, the first parameter in a class method is conventionally CLS-compliant, and Python automatically passes the class name (class space) to the CLS.
class A: def func (self): # normal method print(self) @classmethod # class method def func1 (CLS): Print == A () a1.func1 () # Object calls the class method, and the CLS gets the class itself.
Usage scenarios for class methods:
1. Some methods in the class do not require the participation of the object
class A: ' Ale ' = 1 @classmethod def func1 (CLS): # This method requires no object involvement return cls.name + str (cls.count + 1= A ()print(A1.FUNC1 ( ))print(A.FUNC1 ())
2. Change the static variables in the class.
3. In inheritance, the parent class gets the class space of the subclass.
It is also possible for a method in the parent class to get arbitrary values of the subclass space without using a class method
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 ()
Three. Static methods
A static method is a function in a class that does not require an instance. Static methods are mainly used to store logical code, mainly some logic belongs to the class, but there is no interaction with the class itself, that is, in a static method, the operation of the methods and properties in the class is not involved. It can be understood that a static method exists in the namespace of this class. In fact, before Python introduces static methods, it is common to create functions in the global namespace
Static methods for @staticmethod decoration
Benefits:
Code block clear
Improved reusability
Python Polygon Objects (properties, class methods, static methods)