I. Definitions of classes and constructors
Class name (object):
def __init__ (Self,name,score):
Self.name = Name
Self.score = Score
def show_info (self):
Print ("Name=", Name, "Score=", score)
Class names are usually uppercase
Second, through the variable generation instance
Student1 = Student ("CQ", 100)
Third, free to add properties to an object instance
Student1 = Student ("CQ", 100)
Student1.school = "School"
Iv. Restriction of access rights
Name:public, accessible to the outside world
__NAME__: Special, accessible to the outside world
__name: Private
_name: Private, accessible by the outside world, but please treat it as private
V. Obtaining object information
Type (object)
Type (123) ==int
Import types
Type (FN) = types. Functiontype #判断是否为函数类型
Type (fn) = = types. Builtinfunctiontype
Type (fn) = = types. Lambdatype
Type (fn) = = types. Generatortype
Isinstance (object, type)
Dir (object)
Vi. Special methods of __xx__
Similar to __xx__ is a special method that has a special purpose in Python, such as using the Len () function to automatically invoke the __len__ in the object
Vii. Dynamic addition of instance properties
Object. Property = property Value
Viii. class Properties
Class properties are classes and can be defined directly in a class, but their instances can also access class properties
Class Person:
Name = "CQ"
def __init__ (self):
Pass
Nine, dynamic binding method
def show_info (self):
Print ("Hello world!")
From types Import methodtypes
S.show_info = Methodtypes (Show_info (), s)
S.show_info ()
X. Dynamic Binding class method
From types Import methodtypes
CALSS S (object):
Pass
Def show (self):
Print ("Hello")
S1 = S ()
S1.show ()
Xi. restricting dynamically added instance properties
The Python language supports restricting instance properties that can be added dynamically, specifying dynamically added properties through __slots__
Class S (object):
__solts__ = ("name", "Age")
12. Setting properties for a class
By using the Python built-in adorner @property you can set the variables in the method to properties, @property set on the Getter method
Class Student (object):
def __init__ (self,name,age):
Self.__name = Name
Self.__age = Age
@property
def name (self):
Return Self.__name
@name. Setter
def name (Self,value):
Self.__name = value
@proprety
def age (self):
Return Self.__age
In this example, Get_name and Set_name are merged to encapsulate the property name for the class, and the age wrapper is set to the read-only property of the class
Python Learning notes (10)