Python object-oriented class attributes and subclass Usage Analysis, python object-oriented
This article describes the attributes and usage of the class of Python object-oriented language. We will share this with you for your reference. The details are as follows:
Class attributes
Class Foo (object): x = 1.5foo = Foo () print foo. x # attributes> 1.5 print Foo. x # Use the class attributes> 1.5foo.x = 1.7 # modify only the attributes of the new instance without changing the class attributes print foo. x >>>> 1.7 print Foo. x >>> 1.5foo.x + = 0.2 # only change the attributes of the new instance, without changing the attributes of the class print foo. x >>>> 1.9 print Foo. x >>> 1.5del foo. x ## Delete the updated instance attribute. By default, the updated instance attribute is "print foo. x >>>> 1.5 print Foo. x >>>> 1.5
Class subclass
Parent class:
class AddrBookEntry(object): "address book entry class" def __init__(self, nm, ph): self.name = nm self.phone = ph print "created instance for:", self.name def updatePhone(self, newph): self.phone = newph print "updated phone# for:", self.name
Subclass:
When a class is derived, the subclass inherits the attributes of the base class. Therefore, EmplAddrBookEntry inherits the updatePhone method of AddrBookEntry. It is best to customize the constructor of the base class. Otherwise, the constructor of the base class will be called. If the subclass overrides the constructor of the base class, the constructor of the base class will not automatically call it unless it is declared.
Class EmplAddrBookEntry (AddrBookEntry): "employee address book entry class" def _ init _ (self, nm, ph, id, em): # override the base class constructor AddrBookEntry. _ init _ (self, nm, ph) self. empid = id self. email = em def updateEmail (self, newem): self. email = newem print "updated e-mail address for:", self. name
Subclass:
john = EmplAddrBookEntry("john doe","408-555-1212", 42, "john@spam.doe")created instance for: john doe>>> john<__main__.EmplAddrBookEntry object at 0x02115FD0>>>> john.name'john doe'>>> john.phone'408-555-1212'>>> john.email'john@spam.doe'>>> john.updatePhone("415-555-1212")updated phone# for: john doe>>> john.phone'415-555-1212'>>> john.updateEmail("john@doe.spam")updated e-mail address for: john doe>>> john.email'john@doe.spam'