python -- member of object-oriented class

Posted by panic! on Mon, 17 Jan 2022 21:54:11 +0100

 1. Class method

1. Create class methods and call

Create class method

class Animal(object):
    def eat(self, food):
        print(f'eating {food}')
    def play(self):
        print('eating')
    def sleep(self):
        print('sleeping')

Call class method

When called, the object is used Call as an instance method

dog = Animal()   #Instantiate object
dog.eat('meat')    #Calling a method through an instance object
dog.play()    #Calling a method through an instance object
dog.sleep()    #Calling a method through an instance object

Role of self

First of all, it is clear that self exists only in the methods of the class, and independent functions or methods do not have to have self. Self is necessary when defining the methods of a class, although it is not necessary to pass in the corresponding parameters when calling.

Self name is not necessary. In python, self is not a keyword. You can define it as a or b or other names, but it is agreed to be vulgar (in order to unify with other programming languages and reduce the difficulty of understanding). Don't be different. Everyone won't understand it.

There is no error in changing self to myname in the following example:

class Animal(object):
    def eat(cls, food):
        print(f'eating {food}')

dog = Animal()
dog.eat('meat')

 

Self refers to the class instance object itself (Note: not the class itself). In the following example, self points to the dog instance of the Animal class

class Animal(object):
    def eat(self, food):
        print(f'eating {food}')

dog = Animal()
print(dog)

#Operation results:<__ main__. Animal object at 0x020AE508>

If self points to the class itself, which one does self point to when there are multiple instance objects? Examples are as follows:

class Animal(object):
    def eat(self, food):
        print(f'eating {food}')

dog = Animal()
pig = Animal()

So:

self needs to be defined when it is defined, but it will be automatically passed in when it is called.

The name of self is not stipulated to be dead, but it's better to use self as agreed

self always refers to the instance of the class at the time of the call

2. __init__ Initialization method

Init is preceded by two underscores_ init_ _ The initialization method is called automatically when instantiating an object

class Animal(object):
    def __init__(self):
        print("I'am an animal")

    def eat(self, food):
        print(f'eating {food}')

    def play(self):
        print('playing')

    def sleep(self):
        print('sleeping')

dog = Animal()     #Automatically called when instantiating__ init__ method
#Operation results: I'am a animal

2. Class attribute

 1. Instance properties

The attributes defined in an instance are called instance attributes. They are generally statically defined and are usually defined in__ init__ In the initial method; It can also be defined dynamically and externally. The following example

class Animal(object):
    def __init__(self, name, age):
        self.name = name    #Instance properties
        self.age = age      #Instance properties

    def eat(self, food):
        print(f'{self.name} eating {food}')

    def play(self):
        print(f'{self.age}-year-ols {self.name} is playing')

    def sleep(self):
        print('sleeping')


dog = Animal('Teddy', 6)        #Create instance object, and
dog.gender = 'common'        #Define the dynamic instance property through the instance object. This property is dog Exclusive
dog.play()      #Call instance object
print(dog.gender)       #Print instance properties
print(dog.name)     #Call the instance property through the instance object and print

"""
6-year-ols Teddy is playing
 common
Teddy

"""


pig = Animal('Paige', 3)      #Create instance object
pig.play()      #Call instance object
print(pig.name)     #Call the instance property through the instance object and print
print(pig.gender)       #Print instance properties-----Report an error because gender yes dog Object specific properties

"""
    print(pig.gender)       #Print instance properties
AttributeError: 'Animal' object has no attribute 'gender'
3-year-ols Paige is playing
Paige
"""

 2. Class attribute (class variable)

  • Private attribute: if the name of the attribute starts with two underscores, it is a private type; Can only be called within a class

  • Public attribute: if the name of the attribute does not start with two underscores, it is a public attribute; Both inside and outside the class can be called

class Animal(object):
    age = 5       #Class attribute (public)
    __gender = 'mother'       #Class properties (private)

    def __init__(self, name):
        self.name = name    #Instance properties

    def eat(self, food):
        print(f'{self.name} eating {food}')
        print(Animal.__gender)      #Pass within class Animal Object calls private class properties

    def play(self):
        print(f'{self.age}-year-ols {self.name} is playing')

    def sleep(self):
        print('sleeping')

dog = Animal('Teddy')       #Instantiate object
dog.eat('meat')     #Calling instance methods by instantiating objects
print(f"{dog.name}'s age is {dog.age}")      #Print class properties through instance objects: age----5
print(dog.__gender)     #An error is reported. Private class properties cannot be called outside the class through the instance object
print(Animal.__gender)     #An error is reported. Private class properties cannot be called outside the class through the instance object

pig = Animal('Paige')       #Instantiate object
print(f"{pig.name}'s age is {pig.age}")        #Print class properties through instance objects: age---5

print(f"Animal's age is {Animal.age}")       #Print class properties: age ---5

 3. Modify class properties through instance properties

class Animal(object):
    age = 5     #Class properties (shared)

    def __init__(self, name):
        self.name = name    #Instance properties

    def eat(self, food):
        print(f'{self.name} eating {food}')

    def play(self):
        print(f'{self.age}-year-ols {self.name} is playing')

    def sleep(self):
        print('sleeping')

dog = Animal('Teddy')       #Instantiate object
dog.age = 8     #Modify class properties through instance properties
print(f"{dog.name}'s age is {dog.age}")      #Print instance properties
del dog.age     #Delete instance properties
print(f"{dog.name}'s age is {dog.age}")      #Print class properties

pig = Animal('Paige')       #Instantiate object
print(f"{pig.name}'s age is {pig.age}")        #Print class properties through instance objects: age---5

Animal.age = 10     #Modify class properties
print(f"Animal's age is {Animal.age}")       #Print class properties: age ---10