python day4

python day4

object oriented

Get object information

getattr(), hasattr(), setattr() operate on class attributes and methods

getattr(对象, 属性)
Gets the value of the attribute, or if the attribute does not exist AttributeError.
getattr(对象, 属性, 返回默认值)
getattr(obj, 'y', 404)
If the y attribute does not exist, return 404

hasattr(对象, 属性)
True、False

setattr(对象, 属性, 属性值)
Set properties and assign values ​​to objects

Used to dissect the object when you don't know the information about the object. Don't use it normally.

Object Properties and Class Properties

In addition to the constructor, the properties of an object can also be assigned properties after the object is created.
That is, object binding properties

class Student(object):

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

xiaoming = Student('xiaoming')
xiaoming.age = 8

class attribute

class Student(object):
    name = 'student'

The class attribute
Student.name
can the object:
xiaoming.name
the premise is that the object does not have an attribute with the same name as the class attribute.
If object attribute and the class attribute have the same name, then using the object to call, due to the problem of priority, the class attribute will be shielded and the object attribute will be called.
Class properties can only be accessed after the object properties are removed.

In order to count the number of students, you can add a class attribute to the Student class. Each time you create an instance, the attribute will automatically increase:

# -*- coding: utf-8 -*-

class Student(object):
    count = 0

    def __init__(self, name):
        self.name = name
        Student.count += 1

Object-Oriented Advanced Programming

Encapsulation, inheritance, polymorphism, object-oriented three-way axes
Python also has advanced features:
multiple inheritance, custom classes, metaclasses

use__slots__

Dynamic binding allows us to bind properties and methods to objects outside of the class

# -*- coding: utf-8 -*-

class Student(object):
    pass

liupangzi = Student()
liupangzi.name = 'liupz'

def set_age(self, age):
    self.age = age

from types import MethodType
liupangzi.set_age = MethodType(set_age, liupangzi)
liupangzi.set_age(25)

Bind to an object, and the new object created in addition still does not have these properties and methods
You can bind methods to a class, so that all objects will have these methods

Student.set_age = set_age

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325587221&siteId=291194637