Initialize Instance properties: Enter the keyword information attr= ' attr1 ' can be used with kw.iteritems ()
class Person (object): def __init__ (self,name,gender,birth,**kw): self.name=name Self.gender=gender Self.birth=birth for k,v in Kw.iteritems (): setattr (self,k,v) xiaoming = person (' Xiao Ming ', ' Male ', ' 1990-1-1 ', job= ' Student ') print Xiaoming.nameprint xiaoming.job
Access restrictions: Variables that begin with a double underscore cannot be accessed externally
class Person (object): def __init__ (self, Name, score): self.name=name self.__score=scorep = person (' Bob ') , P.__score) Print P.nameprint
Define class Properties: Properties that are directly bound to a class do not need to create an instance and can be accessed directly with the class name (class properties and instance property conflicts: First look for an instance attribute assignment or reference and then the Class property)
class Person (object): count = 0 def __init__ (self,name): self.name=name person.count=person.count+ 1P1 = person (' Bob ') print PERSON.COUNTP2 = person (' Alice ') print PERSON.COUNTP3 = person (' Tim ') print Person.count
Define instance methods: an instance is a function defined in a class, and its first argument is always self, pointing to the instance itself that invokes the method, and the other arguments are exactly the same as a normal function
class Person (object): def __init__ (self, Name, score): self.name=name self.__score=score def get_ Grade (self): return self.__scorep1 = person (' Bob ', ' all ') P2 = person (' Alice ', ' + ') P3 = person (' Tim ', ') print P1.get_grad E () print p2.get_grade () print P3.get_grade ()
Add a method to an instance dynamically: the instance method that we define in class is actually a property, which is actually a function object:
Import Typesdef Fn_get_grade (self): if Self.score >=: return ' A ' if Self.score >=: return ' B ' return ' C ' class Person (object): def __init__ (self, Name, score): self.name = name Self.score = SCOREP1 = person (' Bob ', p1.get_grade) = types. Methodtype (Fn_get_grade, p1, person) #将fn_get_grade绑定到P1实例print p1.get_grade () # = + AP2 = person (' Alice ', 65) Print P2.get_grade () # error:attributeerror: ' Person ' object with no attribute ' Get_grade ' # because P2 instance is not bound Get_grade
Class method: Before defining a method, add @classmethod to the class method class method cannot get the instance information class method input to pass in a class object
class Person (object): __count = 0 @classmethod def how_many (CK): return ck.__count def __init__ ( Self,name): self.name=name person.__count=person.__count+1print person.how_many () p1 = person (' Bob ') print Person.how_many ()
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python advanced Three: Object-oriented Basics