classes in Python (top)
In Python, you can define your own classes by using the Class keyword, and then create instance objects from a custom class object class.
For example, the following creates a student class and implements the initialization function "__init__" for this class:
Class Student (object):
count = 0 Books
= []
def __init__ (self, Name, age):
self.name = name
self.age = Age Pass
Next, take a look at the classes in Python from the student class above. Data Properties
In the student class above, the "count" books "name" and "age" are all referred to as the data properties of the class, but they are divided into class data properties and instance data properties. class data properties and instance data properties
First look at a piece of code that shows the access to class data properties and instance data properties, respectively:
Student.books.extend (["Python", "JavaScript"])
print "Student book list:%s"%student.books
# class can add Class attribute after class defination
student.hobbies = ["reading", "Jogging", "swimming"]
print "Student hobby List:%s '%student.hobbies
print dir (Student)
print
wilber = Student (' wilber ')
print '%s is%d years Old '% (Wilber.name, wilber.age)
# class instance can add new attribute
# "Gender" is the instance attribute only B Elongs to wilber
wilber.gender = "male"
print '%s is%s '% (Wilber.name, Wilber.gender)
# class instance can Access class attribute
print dir (Wilber)
wilber.books.append ("C #")
print wilber.books
print would
= Student ("'ll")
print "%s is%d years old" (Will.name, Will.age)
# 'll shares the same class Attribute with Wilber
# 'll don ' t have the "gender" attribute that belongs to Wilber
print dir ('ll)
print Will.books
Either by using the built-in function dir (), or by accessing the dictionary property __dict__ of the class, both of these ways can see what properties the class has, and the output of the code is:
For class data properties and instance data properties, can be summed up as: class data attributes belong to the class itself, you can access/modify class names through the class name can also be accessed/modified by all instances of the class after the class definition, you can dynamically add class data properties by class name, and the new class properties are also shared by class and all instances Instance data properties can only be accessed through an instance after the instance is generated, and the instance data properties are added dynamically, but these instance data properties belong only to that instance 's special class property
For all classes, there is a special set of properties:
Class properties |
meaning |
__name__ |
Name of Class (string) |
__doc__ |
Document string for Class |
__bases__ |
Group of all parent classes of the |
__dict__ |
A dictionary of the properties of a class |
__module__ |
module to which the class belongs |
__class__ |
Type of class object |
These properties allow you to get some information about the student class:
Class Student (object): ' ' is '
a Student class '
count = 0 Books
= []
def __init__ (self, NA Me, age):
self.name = name
Self.age = Age
pass
print student.__name__
print student.__doc__
Print student.__bases__ print
student.__dict__ print
student.__module__
print Student.__class
The code output is:
Property Hide
It is understood from the above that the class data attribute belongs to the class itself and is shared by all instances of that class, and that the class attribute can be accessed/modified through an instance. However, it is important to be cautious when accessing class properties through an instance, because a property "hidden" situation may occur.
Continue using the student class above to see attribute hiding:
Wilber = Student ("wilber")
print "Student.count is Wilber.count:", Student.count
is Wilber.count Wilber.count = 1
print ' Student.count is wilber.count: ', Student.count is wilber.count
print student.__dict__< C4/>print wilber.__dict__
del wilber.count
print "Student.count is Wilber.count:", Student.count is Wilber.count
Print
Wilber.count + + + 3
print "Student.count is Wilber.count:", Student.count is Wilber.count
print student.__dict__
print wilber.__dict__
del wilber.count
print
print "Student.books is wilber.books: ', Student.books is wilber.books
wilber.books = [' C # ', ' Python ']
print ' student.books is Wilbe R.books: ", Student.books is wilber.books
print student.__dict__
print wilber.__dict__
del Wilber.books
print ' student.books is wilber.books: ', Student.books is wilber.books
print
Wilber.books.append ("CSS")
print "Student.books is wilber.books:", Student.books is wilber.books
print student.__dict__
Print wilber.__dict__
The output of the code is:
Analyze the output of the above code: for the immutable type of class attribute Student.count, it can be accessed through an instance Wilber, and "Student.count is Wilber.count" when assigned through an instance/ When you modify the Count property, a count instance property is created for instance Wilber, at which point,"Student.count is not Wilber.count" when passed "Del Wilber.count" After the statement deletes the Count property of the instance, it becomes "Student.count is Wilber.count" again
The same is true for class property student.books of mutable types, which can be accessed through instance Wilber, and "Student." The books are Wilber. Books " When you assign the books property through an instance, a new books instance property is created for the instance Wilber, at which point," Student. The books are not Wilber. Books " when passed" Del Wilber. Books "statement deletes the books property of an instance and becomes " Student again. " The books are Wilber. Books " When you modify the books property through an instance, you modify the memory address that wilber.books points to (that is, student.books), and at this point," Student. The books are Wilber. Books "
note that although class properties can be accessed through instances, it is not recommended to do so, preferably through class names to access class properties, thereby avoiding the hassle of property concealment. Method
In a class, there may be three methods, instance methods, static methods, and class methods, and here's a look at the differences between the three methods. instance Method
The first argument of an instance method must be "self" and "self" is similar to "this" in C + +.
An instance method can only be invoked through a class instance, at which point "self" represents the class instance itself. The properties of an instance can be accessed directly through "self".
Class Student (object): ' ' is '
a Student class '
count = 0 Books
= []
def __init__ (self, NA Me, age):
self.name = name
Self.age = Age
def printinstanceinfo (self):
print '%s is%d years old '% (SELF.N Ame, Self.age)
pass
wilber = Student ("Wilber",)
Wilber.printinstanceinfo ()
class Method
Class methods use the CLS as the first parameter, the CLS represents the class itself, and the @classmethod adorner is defined. The CLS can access the related properties of the class.
Class Student (object): ' ' is '
a Student class '
count = 0 Books
= []
def __init__ (self, NA Me, age):
self.name = name
Self.age = Age
@classmethod
def printclassinfo (CLS):
print Cls.__name __
Print DIR (CLS)
pass
student.printclassinfo ()
wilber = Student ("Wilber")
Wilber.printclassinfo ()
The output of the code, as you can see from this code, is that the class method can be accessed through the class name or through an instance.
static Method
Unlike instance methods and class methods, static methods have no parameter restrictions, require neither instance parameters nor class parameters, and use @staticmethod adorners when defined.
Like similar methods, static methods can be accessed through class names or through instances.
Class Student (object): ' ' is '
a Student class '
count = 0 Books
= []
def __init__ (self, NA Me, age):
self.name = name
Self.age = Age
@staticmethod
def printclassattr ():
print Student.count
print student.books
pass
student.printclassattr ()
wilber = Student ("Wilber", 28)
wilber.printclassattr ()
The main difference between the three methods is the parameter, the instance method is bound to an instance and can only be invoked through an instance, but for static methods and class methods, it can be invoked by both the class name and the instance. Access Control
There are no access-controlled keywords in python, such as private, protected, and so on. However, in the Python code, there are conventions for access control. Single Underline "_"
In Python, the single underline "_" to achieve module-level privatization, general agreement with the single underline "_" variables, functions for the module private, that is, "from modulename import *" will not introduce a single underscore "_" variables, functions.
Now there is a module lib.py, the content is as follows, the module in a variable name and a function name, respectively, with "_" Start:
Numa = ten
_numa =
def printnum ():
print "NUMA is:", Numa
print "_numa is:", _numa
def _printnum ():
print ' Numa is: ', Numa
print ' _numa is: ', _numa
After introducing the lib.py module with the following code, all the variables and functions beginning with "_" are not introduced, and if Access throws an exception:
From Lib Import *
print NumA
printnum ()
print _numa
#print _printnum ()
double underline "__"
For class attributes in Python, a degree of privatization can be achieved by using a double underscore "__", since properties that begin with a double underscore are "confused" (mangling) at run time.
In the student class, a "__address" attribute is added:
Class Student (object):
def __init__ (self, Name, age):
self.name = name
Self.age = Age
self.__ Address = "Shanghai"
pass
wilber = Student ("Wilber",)
print wilber.__address
When this property is accessed through an instance Wilber, an exception is given, indicating that the property "__address" does not exist.
In fact, through the built-in function dir () you can see some of the original, "__address" property at run time, the property name was changed to "_student__address" (the property name before the addition of a single underline and class name)
>>> wilber = Student ("Wilber")
>>> dir (Wilber)
[' _student__address ', ' __class__ ', ' __ Delattr__ ', ' __dict__ ', ' __doc__ ', ' __form
at__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __module__ ', ' __new __ ', ' __r
educe__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ',
' __weakref__ ', ' age ', ' name '
>>>
So, even if it is a double underline, there is no privatization of the property, because the "__address" attribute can be accessed directly in the following way:
>>> wilber = Student ("Wilber")
>>> print wilber._student__address
Shanghai
> >>
Another important goal of the double underline is to avoid a subclass of a conflict with a property with the same name as the parent class.
Look at one of the following examples: