Object oriented Python

Posted by godfrank on Wed, 09 Mar 2022 12:35:05 +0100

8. Class member descriptor (attribute)

  • The member description of a class is a way to create a member property of a class for related operations in the class
    • Get: operation to get the property
    • set: modify or add attributes
    • delete: the operation of deleting attributes
  • If you want to use the member descriptor of a class, there are probably three methods
    • Using classes to implement descriptors
    • Use attribute modifiers
    • Use property function
      • The property function is simple
      • property(fget, fset, fdel, doc)
  • Either modifier is used to control the member properties accordingly
    • Class method: applicable to multiple attributes in multiple classes sharing the same descriptor
    • property: applicable to the current class. It can control multiple properties in a class
    • Attribute modifier: applicable to the current class. It controls an attribute in a class

9. Built in properties of class

    __dict__: Displays the membership of a class in a dictionary
    __doc__: Get the document information of the class
    __name__: Get the name of the class. If used in a module, get the name of the module
    __bases__: Get all the parent classes of a class and display them as tuples
    
Copy code

10. Common magic methods of class

  • Magic method is a method that does not need to be called manually. It is basically triggered automatically at a specific time
  • The unified feature of magic method. The method name is wrapped by two underscores before and after
  • Operation class
    • __ init__: Constructor
    • __ new__: Object instantiation method. This magic method is special and generally does not need to be used
    • __ call__: Object is triggered when the function is used
    • __ str__: When an object is used as a string
    • __ repr__: Return string
  • Descriptor correlation
    • __set__
    • __get__
    • __delete__
  • Attribute operation related
    • __ getattr__: Triggered when a non-existent property is accessed
    • __ setattr__: Triggered when the member property is set
      • Parameters:
        • self is used to get the current object
        • The name of the property to be set, which appears as a string
        • The value that needs to be set for the property name
      • Function: verify or modify the attribute settings
      • Note: the attribute cannot be assigned in this method, otherwise it will be an endless loop
  • Arithmetic related magic method
    • __ gt__: Function triggered when making greater than judgment
      • parameter
        • self
        • The second parameter is the second object
        • The return value can be any value. It is recommended to return Boolean value

11. Three methods of class and object

  • Example method
    • Methods that can only be used by instantiating an object may need to be completed by the methods of other objects of the object
  • Static method
    • There is no need to instantiate, and it can be accessed directly through classes
  • Class method
    • No instantiation required
# Attribute case
# Create a Student class to describe the Student class
# Students have student Name attribute
# But the name format is not uniform
# You can add a function and call it automatically, but it's stupid
class Student():
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
        # If you don't want to change the code
        self.setName(name)
        
    # Introduce yourself
    def intro(self):
        print("Hai, my name is {0}".format(self.name))
        
    def setName(self, name):
        self.name = name.upper()
        
s1 = Student("RUO Chen", 19.8)
s2 = Student("michi stangle", 24.0)
s1.intro()
s2.intro()
Copy code
Hai, my name is RUO CHEN
Hai, my name is MICHI STANGLE
 Copy code
# propertya case
# Define a Person class with name and age attributes
# For any name entered, we want to save it in uppercase
# For age, we hope to save it in integer internally
# x = property(fget, fset, fdel, doc)
class Person():
    '''
    This is a person, a noble person, a person who is divorced from vulgar taste
    He also has fucking attributes
    '''
    # The function name can be arbitrary
    def fget(self):
        return self._name * 2
    
    def fset(self, name):
        # All entered names are saved in uppercase
        self.name = name.upper()
    def fdel(self):
        self._name = "NoName"
        
    name = property(fget, fset, fdel, "yes name Operate")
Copy code
# Examples of built-in properties of classes
print(Person.__dict__)
print(Person.__doc__)
print(Person.__name__)
# Display all parent classes in tuple form
print(Person.__bases__) 
Copy code
{'__module__': '__main__', '__doc__': '\n    A man who breaks away from vulgar taste is a noble man\n    He also has fucking attributes\n    ', 'fget': <function Person.fget at 0x000001FBBD3AFBF8>, 'fset': <function Person.fset at 0x000001FBBD3AF9D8>, 'fdel': <function Person.fdel at 0x000001FBBD3AF8C8>, 'name': <property object at 0x000001FBBD3B7BD8>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>}

    This is a person, a noble person, a person who is divorced from vulgar taste
    He also has fucking attributes
    
Person
(<class 'object'>,)
Copy code
# init example
class A():
    def __init__(self, name = 0):
        print("Ha ha, I was called")
        
a = A()
Copy code
Ha ha, I was called
 Copy code
# __ call__  give an example
class A():
    def __init__(self, name = 0):
        print("Ha ha, I was called")
        
    def __call__(self):
        print("I was called again")
        
a = A()
a()
Copy code
Ha ha, I was called
 I was called again
 Copy code
# __ str__  give an example
class A():
    def __init__(self, name = 0):
        print("Ha ha, I was called")
        
    def __call__(self):
        print("I was called again")
        
    def __str__(self):
        return '666'
        
a = A()
print(a)
Copy code
Ha ha, I was called
666
 Copy code
# __getattr__
class A():
    name = "NoName"
    age = 18
    
    def __getattr__(self, name):
        print("Can't find")
        print(name)
    

        
a = A()
print(a.name)
print(a.addr)
Copy code
NoName
 Can't find
addr
None
 Copy code
# __ setattr__  case
class Person():
    def __init__(self):
        pass
    
    def __setattr__(self, name, value):
        print("Set properties:{0}".format(name))
        # The following statement will cause problems, such as an endless loop
        # self.name = value
        # In this case, in order to avoid dead loop, it is required to call the parent magic function uniformly
        super().__setattr__(name, value)
p = Person()
print(p.__dict__)
p.age = 18
 Copy code
{}
Set properties: age
 Copy code
# __gt__

class Student():
    def __init__(self, name):
        self._name = name
        
    def __gt__(self, obj):
        print("ha-ha,{0} Will compare {1} Is it big?".format(self, obj))
        return self._name > obj._name
    
stu1 = Student("one")
stu2 = Student("two")
print(stu1 > stu2)
Copy code
ha-ha,<__main__.Student object at 0x000001C15772EB38> Will compare <__main__.Student object at 0x000001C15772E550> Is it big?
False
 Copy code
# Cases of three methods
class Person():
    # Example method
    def eat(self):
        print(self)
        print("Eating......")
    # Class method
    # The first parameter of a class method is generally named cls, which is different from self
    @classmethod
    def play(cls):
        print(cls)
        print("Playing......")
        
    # Static method
    # You don't need to represent yourself or a class with the first parameter
    @staticmethod
    def say():
        print("Saying......")
        
yueyue = Person()

# Example method
yueyue.eat()
# Class method
Person.play()
yueyue.play()
# Static method
Person.say()
yueyue.say()
Copy code
<__main__.Person object at 0x000001C157766710>
Eating......
<class '__main__.Person'>
Playing......
<class '__main__.Person'>
Playing......
Saying......
Saying......

 

Topics: Python