Classes and instances
A class is associated with an instance: A class is the definition of an object, and an instance is a "real object" that holds the specific information of the object defined in the class.
The following example shows how to create a class:
Class Mynewobjecttype (Bases):
' Create Mynewobjecttype class '
class_suite
The keyword is class, followed by a class name. Then there is the class code that defines the class. This is usually made up of a variety of definitions and statements. The biggest difference between a new class and a classic class declaration is that all new classes must inherit at least one parent class, and the parameter bases can be one (single inheritance) or multiple (multiple inheritance) for the inherited parent class.
The process of creating an instance is called instantiation, and the procedure is as follows (note: No new keyword is used):
Myfirstobject = Mynewobjecttype ()
The class name appears in the form of a function call using the familiar function operator (()). Then you usually assign the new instance to a variable. The assignment is not syntactically necessary, but if you do not save the instance to a variable, it is useless and will be reclaimed by the automatic garbage collector because any reference to that instance. So, all you've just done is allocate a piece of memory for that instance and then release it.
Classes can be either simple or complex, depending on your needs. In the simplest case, the class is used only as a namespace (namespace). This means that you keep the data in variables, group them by namespace, and put them in the same relational space-the so-called relationship is identified by using the standard Python period attribute. For example, you have a class that has no attributes of its own, use it to provide only a namespace for the data, let your class have the same attributes as the structure in C (structure), or in other words, a class that shares namespaces only as container objects.
Examples are as follows:
Class MyData (object):
pass
mathobj = MyData ()
mathobj.x = 4
mathobj.y = 5
mathobj.x + mathobj.y
9
mathobj.x \\* mathobj.y
20
Method
in Python, the method definition is in the class definition, but can only be invoked by the instance. That is, the final way to invoke a method must be this: (1) Defining the Class (and method), (2) Creating an instance, (3) The last step, invoking the method with this instance. For example:
Class Mydatawithmethod (object): # defines the category
def printfoo (self): # define method
print ' you invoked Printfoo ()! '
The self argument here, which exists in all the method declarations. This parameter represents the instance object itself, and when you invoke the method with an instance, it is passed to the method by the interpreter, so you do not need to pass self in because it is automatically passed in.
For example, if you have a method with two parameters, all your calls only need to pass the second argument.
Here's how to instantiate this class and call that method:
> > > myobj = Mydatawithmethod ()
> > > Myobj.printfoo () You
invoked Printfoo ()!
\\_init\\ (), is a special method. In Python, \\init\\ () is not actually a constructor. You didn't call "new" to create a new object. (Python has no "new" keyword at all). Instead, after Python creates the instance, in the instantiation process, the \\init\\_ () method is invoked, and when a class is instantiated, additional behavior can be defined, such as setting the initial value or running some preliminary diagnostic code-primarily after the instance is created, and before the instantiation call returns the instance, To perform specific tasks or settings.
Create a class (class definition)
Class Addrbookentry (object):
' Address Book entry class '
def __init__ (self, NM, ph): # definition builder
self.name = n M # set name
self.phone = ph # set phone
print ' Created instance for: ', Self.name
def updatephone (self, NEWPH): # define method
Self.phone = newph
print ' Updated phone# for: ', self.name
In the definition of the Addrbookentry class, two methods are defined: \\_init\\ () and Updatephone (). \\init\\ () is invoked when instantiated, that is, when Addrbookentry () is called. You can think of instantiation as an implicit invocation of \\init\\ (), because the arguments passed to Addrbookentry () are exactly the same as the parameters that \\init\\_ () received (except self, which is automatically passed).
Creating an instance (instantiated)
> > > John = addrbookentry (' John Doe ', ' 408-555-1212 ') # Create an instance for John Doe
> > > Jane = addrbookentry ( ' Jane Doe ', ' 650-555-1212 '] # Create an instance for Jane Doe
This is the instantiation call, which automatically invokes \\_init\\ (). Self automatically passes the instance object to \\init\\_ ().
In addition, if there is no default parameter, the two parameters passed to \\_init\\_ () are required when instantiated.
accessing instance Properties
> > > John
> > > John.name
> > > Jane.name
> > > Jane.phone
Once the instance has been created, it is possible to confirm whether our instance properties were actually set by \\_init\\_ () during the instantiation process. We can see what kind of object it is by using an interpreter "dump" instance.
Method call (through an instance)
> > > John.updatephone (' 415-555-1212 ') # update John Doe's phone
> > > John.phone
The Updatephone () method requires a parameter (excluding self): a new phone number. After Updatephone (), check the instance properties immediately to verify that they are in effect.
The
method and the summary of the property
are directly on the code and are already commented on inside
#coding: UTF8 name = ' yangyanxing ' class Test (): Class Kevin (): var1 = ' I am the inner class ' name = ' Kvein ' gae = ' de '
F fun1 (self): print self.name print ' I am public method ' self.__fun2 () #可以通过公有就去来调用私有方法, you can make changes to Def __fun2 (self) in the process of calling: print ' I am private method ' @classmethod def fun3 (self): #可以不通过实例来访问这个类方法 print ' # ' *40 print self.name print ' I am a class Method ' @staticmethod #静态方法 and is a method that can be accessed without the instance object, but not with the self Def fun4 (): Print test.name print name #这里的name是全局 Variable test.fun3 () print ' I am static method ' Print Test.name #公有属性可以直接方法 without instantiating the object Yang = Test () #实例化一个类 Interyang = Test.kevin () #实例化一个内部类 yang.fun1 () #方法类里面的公共属性 Print Interyang.var1 # accesses the properties in the Inner class Test.fun3 () #访问类方法 test.fun4 () #coding: UTF8 class Test ( ): Var1 = ' class's public property ' __var2 = ' class's private attribute ' def fun (self): self.var2 = ' public attribute of object ' # here defines the public property of an object self.__var3 = ' to The private property ' # Here defines an object's private property VAR4 = ' function's local variable ' #这里定义了一个函数的局部变量, which var4 only use Kevin = Test () inside the function #实例了一个对象 Yang = Test () #又实例 Another object, print Kevin.var1
# #print Kevin.__var2 #这里将无法访问 kevin.fun () print kevin.var2 #在没有调用fun函数之前是没有var2的 # #print Kevin.__var3 object's private property is not callable # #pr
int Yang.var2 #这里因为没有调用yang的fun方法, so still can't access Yang's var2
To create a child class
subclass by inheritance is a way to create and customize a new type, and the new class retains all the attributes of the existing class without altering the definition of the original class. For a new class type, this new subclass can customize the specific functionality that belongs to it. In addition to relationships with parent or base classes, subclasses are no different from normal classes, and are instantiated like generic classes. Note that the parent class is mentioned in the subclass declaration:
Class Empladdrbookentry (addrbookentry):
"' Employee Address Book Entry class ' ' # Employee Directory Class
def __init__ (self, NM, ph, ID, EM):
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
Now we have created the first subclass, Empladdrbookentry. In Python, when a class is derived, subclasses inherit the properties of the base class, so in the above class we not only define the \\_init\\_ (), Updateemail () method, but also empladdrbookentry from Addrbookentry The Updatephone () method is inherited from.
If necessary, each subclass is best defined for its own constructor, or the constructor of the base class is invoked. However, if the subclass overrides the constructor of the base class, the constructor of the base class will not be invoked automatically-so that the constructor of the base class must be explicitly written out before it is executed, as we have above, using addrbookentry.\\_init\\_ () to set the name and phone number. Our subclasses also set another two instance properties on the following lines of the constructor: Employee ID and e-mail address.
Notice here we're going to explicitly pass the self instance object to the base class constructor, because we're not calling that method in the instance but in a subclass instance. Because we do not invoke it through an instance, this unbound method invocation needs to pass an appropriate instance (self) to the method.
Using subclasses
> > > John = Empladdrbookentry (' John Doe ', ' 408-555-1212 ', #, ' John@spam.doe ')
> > > John
> > > John.name
> > > John.phone
> > > John.email
> > > John.updatephone (' 415- 555-1212 ')
> > > John.phone
> > > John.updateemail (' john@doe.spam ')
> > > John.email