Day18: classes and objects

1. Object method

class Class name:
    Class description document
    Class content(Object method, class method, static method + Object attribute, class attribute)

1) Object method

A method is a function defined in a class

1) How to define: directly define (without adding any decorators) that a function in a class is an object method
2) How to call: through 'object Called in the form of xx() '
3) Features: each object method has a default parameter self. When calling an object method through an object, self does not need to pass parameters. The system will automatically pass the current object to self(self: point to who calls)

# Define class
class Person:
    # Define an object method in a class
    def eat(self):
        print('having dinner')

# Create object p1
p1 = Person()
# Calling object methods through objects
p1.eat()

2) Initialization method -__ init __

__ init__ It is a special object method and magic method in python class
Magic method: the method name in the class is__ Start with__ The methods at the end are all magic methods. All magic methods are brought by the system
Magic methods do not need to be called actively by programmers, and the system will call them automatically under specific circumstances
1)__init__ Method is automatically called every time an object is created
2) When creating an object through a class, whether parameters are required or not, several parameters are required by the__ init__ decision

2. Properties

1) Properties in class

#Defining a class is to use code to describe the sum of things with the same characteristics
#If the feature is represented by data, the feature is represented by attributes

1) Class properties
a. How to define: variables directly defined in a class are class attributes
b. How to use: through 'class xx '
c. When to use: class attributes are used when attribute values are not different because of different objects

2) Object properties
a. How to define: take 'self The form XX = value 'is defined in__ init__ Method
b. How to use: through 'objects xx '
c. When to use: object attributes are used when the attribute values are different due to different objects

class A:
    # a and name are class attributes
    a = 10
    name = 'Xiao Ming'

    # b and gender are object attributes
    def __init__(self):
        self.b = 100
        self.gender = 'male'
# Use class properties
print(A.a)
print(A.name)

# Use object properties
x = A()
print(x.b)
print(x.gender)

2. Object attribute default value

1) Method 1: use a fixed value (mainly used when the attribute value is a certain value in most cases and changes in very few cases)
2) Mode 2: in__ init__ There is no default value for the formal parameter provided to assign value to this attribute in (attribute values are generally different; it is required to provide the value of a certain attribute when creating an object)
3) Method 3: in__ init__ The formal parameter assigned to this property is provided in. The formal parameter has a default value

class Person:
    def __init__(self,name,gender='male'):
        self.name = name
        self.age = 18
        self.gender = gender

p1 = Person('Xiao Ming')
p1.age = 19

p2 = Person('floret','female')
p2.age = 20

# Exercise: define the circle class and have attributes: PI and radius. Methods: calculate area and perimeter
class Circle:
    pi = 3.1415926
    def __init__(self,r):
        self.r = r

    def area(self):
        return Circle.pi * self.r ** 2

    def perimeter(self):
        return Circle.pi * self.r * 2
c1 = Circle(10)
print(c1.area())
print(c1.perimeter())

3. Method

1) Object method
a. How to define: direct definition
b. How to call: object xx()
c. Features: the parameter self does not need to be passed. It points to the current object
d. When to use: if you need to use object properties to implement the function of a function, use object methods

2) Class method
a. How to define: add a @ classmethod decorator before defining a function
b. How to call: class xx()
c. Features: cls has its own parameter. When calling, you don't need to pass the parameter. The system will automatically pass the current class to cls
d. When to use: use class methods when you need classes without object properties

3) Static method
a. How to define: add @ staticmethod before defining a function
b. How to call: class xx()
c. Features: no features - no default parameters
d. When to use: static methods are used to implement function functions without classes or objects

class A:
    def func1(self):
        print('Object method')

    @classmethod
    def func2(cls):
        print('Class method')

    @staticmethod
    def func3():
        print('Static method')
a = A()
a.func1()
a.func2()
a.func3()

4. Add, delete, modify and query object attributes

class Student:
    def __init__(self,name,stuid,age = 18):
        self.name = name
        self.age = age
        self.stuid = stuid
        self.score = 0

    # When printing the object of the current class through print, this method will be called automatically, and the return value of this method will be printed (the return value must be a string)
    # Who is printed? self is who
    def __repr__(self):
        # Student No.: xx Name: xxx age: xx score: xxx
        return str(self.__dict__)
stu1 = Student('Xiao Ming','stu001')
print(stu1)

stu2 = ('floret','stu002',20)
print(stu2)

1) Query - get attribute value

Object Object property - gets the value corresponding to the specified property. If the property does not exist, an error is reported
Getattr (object, property name) - get the value corresponding to the specified property. If the property does not exist, an error will be reported
Getattr (object, attribute name, default value) - get the value corresponding to the specified attribute. If the attribute does not exist, no error is reported and the default value is returned

print(stu1.name)
print(getattr(stu1,'name'))

value = input('Please enter the name of the property you want to get:')
print(getattr(stu1,value))

2) Addition and modification

Object Attribute = value - modify the value of the specified attribute if the attribute exists, and add the attribute if the attribute does not exist
Setattr (object, attribute name, value) - modify the value of the specified attribute if the attribute exists, and add the attribute if the attribute does not exist

stu1.name = 'Zhang San'
print(stu1)
stu1.height = 180
print(stu1)

setattr(stu1,'name','Li Si')
print(stu1)
setattr(stu1,'weight',70)
print(stu1)

3) Delete

del object attribute
Delattr (object, attribute name)

del stu1.score
print(stu1)

delattr(stu1,'stuid')
print(stu1)
class B:
    # __ slots__ You can constrain the maximum object properties that an object of the current class can have
    __slots__ = ('x','y','z')
    def __init__(self):
        self.x = 10
        self.y = 20
        self.z = 30
b = B('t',100)

print(b)		# Error reported: typeerror:__ init__ () takes 1 positional argument but 3 were given

Keywords: Python

Added by peppino on Wed, 22 Dec 2021 16:50:26 +0200