Classes and Objects of binding method

Classes and Objects of binding method

class OldboyStudent:
    school = 'oldboy'

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.sex = gender

    def choose_course(self):
        print(f'{self.name} choosing course')

    def func(self):
        print('from func')
  • Class data attributes and function attributes are defined in a namespace for all shared objects with

  • Only data attributes defined object name space, and is unique to the object data attributes

86- classes and objects bound method - bind .jpg

Bound object class

stu1 = OldboyStudent('nick', 18, 'male')
stu2 = OldboyStudent('sean', 17, 'male')
stu3 = OldboyStudent('tank', 19, 'female')

print(stu1.name)
print(stu1.school)
nick
oldboy
  • Class defined function is a function attribute class, a class can use, but use is a normal function of it, implies the need for full compliance with the rules of function parameters, which pass several values ​​to pass several

86- classes and objects bound method - Rules .jpg

print(OldboyStudent.choose_course)
<function OldboyStudent.choose_course at 0x10558e840>
try:
    OldboyStudent.choose_course(123)
except Exception as e:
    print(e)
'int' object has no attribute 'name'

Bound method object

  • Class-defined functions are shared to all objects, the object may be used, and is bound to the subject with,

  • Binding effect: Binding to whom, by whom they should call, who will call who will automatically passed as the first argument

Binding method 86- classes and objects -self.jpg

print(id(stu1.choose_course))
print(id(stu2.choose_course))
print(id(stu3.choose_course))
print(id(OldboyStudent.choose_course))
4379911304
4379911304
4379911304
4384680000
print(id(stu1.school))
print(id(stu2.school))
print(id(stu3.school))
4380883688
4380883688
4380883688
print(id(stu1.name), id(stu2.name), id(stu3.name))
4384509600 4384506072 4384507864
stu1.choose_course()
nick choosing course
stu2.choose_course()
sean choosing course
stu3.choose_course()
tank choosing course
  • Added: class defined functions, classes can really use, but in fact a function of the class definition in many cases are used to bind to the target, so the functions defined in the class should own a parameter self
stu1.func()
from func
stu2.func()
from func

Guess you like

Origin www.cnblogs.com/nickchen121/p/10987600.html