Python learning notes - classes

Python learning notes

Python learning notes (1) -- Fundamentals of language
Python learning notes (2) -- functions
Python learning notes (3) -- class

1, Class introduction

Three characteristics of object-oriented:

  1. encapsulation
  • Ensure data security in objects
  1. inherit
  • It ensures the scalability of objects
  1. polymorphic
  • It ensures the flexibility of the program

Use the class keyword to define a class. The syntax is very similar to that of a function!

class Class name([Parent class]):
class MyClass():
    pass
print(MyClass) # <class '__main__.MyClass'>
Using classes to create objects is like calling a function
mc = MyClass() # mc is the object created through MyClass. mc is an instance of MyClass
mc_2 = MyClass()
mc_3 = MyClass()
mc_4 = MyClass()
# mc mc_2 mc_3 mc_4 are instances of MyClass. They are all class objects

isinstance() is used to check whether an object is an instance of a class

result = isinstance(mc_2,MyClass)
print(result) # False	

Now all the objects we create through the MyClass class are empty objects
That is, there is actually nothing in the object, which is equivalent to an empty box
You can add variables to objects, which are called properties

 Syntax: objects.Attribute name = Attribute value
mc.name = 'Sun WuKong'
print(mc_2.name) # Zhu Bajie

2, Define class

  • Defining variables: public attributes that can be accessed by all instances
  • Defining functions: calling methods, objects Method name ()
# Try to define a class that represents people
class Person :
    # The variables we define in the class will become the public properties of all instances
    # All instances can access these variables
    name = 'swk' # Public property, which can be accessed by all instances

    # Functions can also be defined in a class. The functions defined in a class are called methods
    # These methods are accessible through all instances of the class
    
    def say_hello(self) :
        # Every time a method is called, the parser automatically passes the first argument
        # The first parameter is the object that calls the method itself,
        #   If it is called p1, the first parameter is the p1 object
        #   If it is called p2, the first parameter is the p2 object
        # Generally, we will name this parameter self

        # say_ The hello () method can display data in the following format:
        #   Hello! I'm xxx
        #   Properties in a class cannot be accessed directly in a method
        print('Hello! I am %s' %self.name)

# Create an instance of Person
p1 = Person()
p2 = Person()

# Call method, object Method name ()
# The difference between method calls and function calls
# If it is a function call, several parameters will be passed during the call, and there will be several arguments
# However, if it is a method call, a parameter is passed by default, so at least one formal parameter must be defined in the method


# Modify p1's name attribute
p1.name = 'Zhu Bajie'
p2.name = 'Sand monk'

p1.say_hello() # 'Hello! I'm pig Bajie '
p2.say_hello() # 'Hello! I'm monk Sha '

3, Object initialization (_init__method)

Note__ init__ The first parameter of the method is always self, which represents the created instance itself. Therefore, in__ init__ Method, you can bind various properties to self, because self points to the created instance itself.

Yes__ init__ Method. When creating an instance, you can't pass in empty parameters. You must pass in and__ init__ Method, but self does not need to be passed. The Python interpreter will pass in the instance variable itself:

class Person :
    def __init__(self,name):
        print(self)
        # Initialize properties to the newly created object through self
        self.name = name

    def say_hello(self):
        print('Hello, I'm%s'%self.name)

#When creating an object, you must set the name attribute. If you do not set the object, you will not be able to create it
p1 = Person('Sun WuKong')
p2 = Person('Zhu Bajie')
p3 = Person('Sand monk')
p4 = Person('Tang Monk')

p4.say_hello() # Hello, I'm monk Tang

4, Encapsulation

1. Basic packaging

Encapsulation refers to hiding some properties or methods in an object that you do not want to be accessed externally

How do I get (modify) properties in an object?
You need to provide a getter and setter method so that the property can be accessed externally

  • getter gets the specified property (get# property name) in the object
  • setter is used to set the specified property (set# property name) of the object

Using encapsulation does increase the complexity of class definition, but it also ensures the security of data

1. The attribute name is hidden, so that the caller cannot modify the attribute in the object at will
2. getter and setter methods are added to control whether the property is read-only

  • If you want the property to be read-only, you can directly remove the setter method

  • If you want the property not to be accessed externally, you can directly remove the getter method

    3. Using setter method to set properties can increase data validation and ensure that the data value is correct
    4. Use getter method to get the property and setter method to set the property

  • You can do some other processing while reading and modifying attributes

    5. Use getter method to represent some calculated attributes

class Dog:
    '''
        Represents the class of the dog
    '''
    def __init__(self , name , age):
        self.hidden_name = name
        self.hidden_age = age

    def say_hello(self):
        print('Hello, I'm %s'%self.hidden_name) 

    def get_name(self):
        '''
            get_name()Used to get the object name attribute
        '''    
        # print('user read attribute ')
        return self.hidden_name

    def set_name(self , name):
        # print('user modified attribute ')
        self.hidden_name = name

    def get_age(self):
        return self.hidden_age

    def set_age(self , age):
        if age > 0 :
            self.hidden_age = age    


d = Dog('Wangcai',8)

# d.say_hello()

# Call setter to modify the name attribute 
d.set_name('Xiao Hei')
d.set_age(-10)

# d.say_hello()
print(d.get_age())

2. Hide attributes__ xxx

  • The attribute starting with double underscore is the hidden attribute of the object. The hidden attribute can only be accessed inside the class, not through the object
  • In fact, hiding attributes is just Python automatically changing the name of the attribute
  • It's actually changing the name to_ Class name__ Property name, such as__ name -> _ Person__ name
class Person:
    def __init__(self,name):
        self.__name = name

    def get_name(self):
        return self.__name

    def set_name(self , name):
        self.__name = name

p = Person('Sun WuKong')
print(p.__name)# __ The property at the beginning is hidden and cannot be accessed through the object
# AttributeError: 'Person' object has no attribute '__name'

p.__name = 'Zhu Bajie'
print(p._Person__name) # Sun WuKong

p._Person__name = 'Zhu Bajie'
print(p.get_name()) # Zhu Bajie

3. Property decorator

  1. The property decorator is used to convert a get method into an object's property
  2. After being added as a property decorator, we can use the get method just like calling properties
  3. The method using property decoration must be the same as the property name
class Person:
    def __init__(self,name,age):
        self._name = name
        self._age = age
  
    @property    
    def name(self):
        print('get Method is executed~~~')
        return self._name

    # Decorator of setter method: @ property name setter
    @name.setter    
    def name(self , name):
        print('setter Method called')
        self._name = name        

    @property
    def age(self):
        return self._age

    @age.setter    
    def age(self , age):
        self._age = age   

        

p = Person('Zhu Bajie',18)

p.name = 'Sun WuKong'
p.age = 28

print(p.name,p.age)
# setter method called
# The get method is executed~~~
# Monkey King 28

5, Inherit

1. Succession

Through inheritance, we can make one class get properties and methods in other classes

  • When defining a class, you can specify the parent class (superclass, base class, super) of the current class in parentheses after the class name
    Subclasses (derived classes) can directly inherit all properties and methods in the parent class

  • When creating a class, if the parent class is omitted, the default parent class is object

     Syntax: Class A(B):
    
class Animal:
    def run(self):
        print('Animals can run~~~')

    def sleep(self):
        print('Animals sleep~~~')

class Dog(Animal):
    def bark(self):
        print('Woof, woof~~~') 

    def run(self):
        print('Dog run~~~~')    

class Hashiqi(Dog):
    def fan_sha(self):
        print('I'm a silly husky')      

d = Dog()
h = Hashiqi()

d.run() # Dog run~~~~
d.sleep() # Animals sleep~~~
d.bark() # Woof, woof~~~

  • issubclass() checks whether a class is a subclass of another class
print(isinstance(print , object)) # True

2. Rewrite

If there is a method with the same name as the parent class in the subclass, when calling the method through the subclass instance:

  1. It will call the methods of the subclass instead of the methods of the parent class. This feature is called method override

When we call the method of an object:

  1. Priority will be given to the current object to find whether it has the method. If so, it will be called directly

  2. If not, search the parent class of the current object. If there is one in the parent class, call the method in the parent class directly,

  3. If not, search the parent class of the parent class, and so on until the object is found. If it is still not found, an error is reported

3. Multiple inheritance

Multiple inheritance: you can specify multiple parent classes for a class at the same time

Syntax: class C(A,B):
			pass

6, Polymorphism

class A:
    def __init__(self,name):
        self._name = name

    @property
    def name(self):
        return self._name
        
    @name.setter
    def name(self,name):
        self._name = name   

class B:
    def __init__(self,name):
        self._name = name

    def __len__(self):
        return 10

    @property
    def name(self):
        return self._name
        
    @name.setter
    def name(self,name):
        self._name = name   

class C:
    pass


a = A('Sun WuKong')
b = B('Zhu Bajie')
c = C()

def say_hello(obj):
    print('Hello %s'%obj.name)

say_hello(a) # Hello, Monkey King
say_hello(b) # Hello, pig Bajie

Example of polymorphic function: len ()

  • The reason why an object can get the length through len() is that there is a special method in the object__ len__
  • In other words, as long as there is__ len__ Special method, you can get its length through len()
class B:
    def __init__(self,name):
        self._name = name

    def __len__(self):
        return len(self._name)

    @property
    def name(self):
        return self._name
        
    @name.setter
    def name(self,name):
        self._name = name   

print(len(b)) # 3

7, Properties and methods in class

  1. Class attribute: attributes defined directly in a class are class attributes

    Class properties can be accessed through classes or instances of classes
     Class properties can only be modified through class objects, not instance objects
    
  2. Instance property: the property added through the instance object belongs to the instance property

    Instance properties can only be accessed and modified through instance objects. Class objects cannot be accessed and modified
    
  3. Class method: the method modified by @ classmethod inside the class belongs to class method

    The first argument to a class method is cls,It will also be transmitted automatically, cls Is the current class object
        The difference between class method and instance method. The first parameter of instance method is self,The first parameter of a class method is cls
        Class methods can be called through classes or instances. There is no difference
    
  4. Instance method: all methods with self as the first parameter are instance methods

    Instance methods can be called through instances and classes
               When invoked by instance, the current call object is automatically taken as an example. self afferent
               When called through a class, it is not passed automatically self,At this point, we must pass it manually self
    
  5. Static method: the method modified with @ staticmethod belongs to static method

     Static methods do not need to specify any default parameters. Static methods can be called through classes and instances  
         Static method is basically a method independent of the current class. It is just a function saved to the current class
         Static methods are generally tool methods, independent of the current class
    
class A(object):

    # Class properties
    count = 0
    # Instance properties
    def __init__(self):
        self.name = 'Sun WuKong'

    # Example method
    def test(self):
        print('This is test method~~~ ' , self)    

    # Class method    
    @classmethod
    def test_2(cls):
        print('This is test_2 Method, which is a class method~~~ ',cls)
        print(cls.count)

    # Static method
    @staticmethod
    def test_3():
        print('test_3 Yes~~~')

a = A()
# Instance property. The property added through the instance object belongs to the instance property
a.count = 10
A.count = 100
print('A ,',A.count)
print('a ,',a.count)
print('A ,',A.name)
print('a ,',a.name)

a.test() #Equivalent to A.test(a)

A.test_2() #Equivalent to a.test_2()

A.test_3()
a.test_3()

8, Special method (magic method)

Special methods generally do not need to be called manually, but need to be executed automatically in some special cases

 Special methods are used:__AAA__
class Person(object):
    """human beings"""
    def __init__(self, name , age):
        self.name = name
        self.age = age

    # __ str__ () this special method is called when trying to convert an object to a string
    # Its function can be used to specify the result of converting an object into a string (print function)  
    def __str__(self):
        return 'Person [name=%s , age=%d]'%(self.name,self.age)        

    # __ repr__ () this special method will be called when using the repr() function on the current object
    # Its function is to specify the effect of direct output of objects in 'interaction mode'    
    def __repr__(self):
        return 'Hello'
        
	def __adult__(self):
        return self.age > 17        
        
	def __older__(self , other):
		 return self.age > other.age

p1 = Person('Sun WuKong',18)
p2 = Person('Zhu Bajie',28)

print(p1) # Person [name = Monkey King, age=18]
print(p1.__older__(p2)) # False
if p1 :
    print(p1.name,'I'm an adult')
else :
    print(p1.name,'He's still a minor')
# Monkey King is an adult

Keywords: Python

Added by 22Pixels on Fri, 14 Jan 2022 21:33:07 +0200