1. The public members of the class private members
# 类的私有成员: 私有类的静态属性, 私有类的方法, 私有对象的属性
For the members of each class has two forms:
- Public members can be accessed from anywhere
- Internal method to private members only in class
Restrict access private members and members of the public differ :
1.1 static fields (static properties)
- Public static fields: class can access; inner class can access; derived class can access
- Private static fields: internal class can only access
Public static properties (fields)
class C:
name = "公有静态字段"
def func(self):
print C.name
class D(C):
def show(self):
print C.name
C.name # 类访问
obj = C()
obj.func() # 类内部可以访问
obj_son = D()
obj_son.show() # 派生类中可以访问
# 公有静态字段
Private static attribute (field)
class C:
__name = "私有静态字段"
def func(self):
print C.__name
class D(C):
def show(self):
print C.__name
C.__name # 不可在外部访问
obj = C()
obj.__name # 不可在外部访问
obj.func() # 类内部可以访问
obj_son = D()
obj_son.show() #不可在派生类中可以访问
# 私有静态字段
1.2 the normal field (object attribute)
- Common Public field: an object can be accessed; internal access classes; derived class can access
- Private general fields: internal class can only access;
Public object properties!
class C:
def __init__(self):
self.foo = "公有字段"
def func(self):
print self.foo # 类内部访问
class D(C):
def show(self):
print self.foo # 派生类中访问
obj = C()
obj.foo # 通过对象访问
obj.func() # 类内部访问
obj_son = D();
obj_son.show() # 派生类中访问
# 公有普通字段
Private object attributes
class C:
def __init__(self):
self.__foo = "私有字段"
def func(self):
print self.foo # 类内部访问
class D(C):
def show(self):
print self.foo # 派生类中访问
obj = C()
obj.__foo # 通过对象访问 ==> 错误
obj.func() # 类内部访问 ==> 正确
obj_son = D();
obj_son.show() # 派生类中访问 ==> 错误
# 私有普通字段
1.3 Methodology
- Public methods: an object can be accessed; internal access classes; derived class can access
- Private methods: internal class can only access;
Public methods
class C:
def __init__(self):
pass
def add(self):
print('in C')
class D(C):
def show(self):
print('in D')
def func(self):
self.show()
obj = D()
obj.show() # 通过对象访问
obj.func() # 类内部访问
obj.add() # 派生类中访问
# 公有方法
Private methods
class C:
def __init__(self):
pass
def __add(self):
print('in C')
class D(C):
def __show(self):
print('in D')
def func(self):
self.__show()
obj = D()
obj.__show() # 通过不能对象访问
obj.func() # 类内部可以访问
obj.__add() # 派生类中不能访问
to sum up
For these private members, they use only within the class, you can not be outside the class and derived class to use.
* Ps: have to access private members, it can be the object ._ class __ attribute name, but definitely not !!! *
* Why ._ private members of the class name can access __? Because when you create a class, if you encounter a private members (including private static fields, private common field, private method) it will be saved in memory automatically when the front plus _ the class name. *
2. Other members of the class
Methods include: general methods, static methods and class methods, three methods all belong to the class in memory, the difference lies in the different ways to call
Examples of methods
Definition: The first parameter is an instance of an object, the parameter name is generally agreed as "self", through which pass properties and methods of instances (may also transmit properties and methods and the like);
Call: can only be called by an instance of an object.
Class Methods
Definition: the decorator @classmethod. The first argument must be a class object is the current, this parameter is generally agreed to name "cls", through which to pass the properties and methods (not pass instance attributes and methods) of the class;
Call: class instance object and the object can be called.
Static method
Definition: the decorator @staticmethod. Random parameters, no "self" and "cls" parameter, but the method can not be used in the body of any class or instance attributes and methods;
Call: class instance object and the object can be called.
The method of the bis (will be mentioned later)
Definition: The Double Down is a special method, he is a cool method name with an underscore plus cool underscore method has special significance __ __ method name interpreter provided under the dual method is mainly python source programmers,
We do not use as much as possible in the development of two-under method, but double-depth research methods, we are more conducive to reading the source code.
Call: double under different methods have different trigger modes, like the same organs triggered when Tomb, unknowingly triggered a two-under method, for example: the init
2.1 class method
Decorator @classmethod.
class A:
def func(self):
print('实例方法')
@classmethod
def cls_func(cls):
# print(f'cls---->{cls}')
obj = cls()
print(obj)
print('类方法')
print(A)
A.cls_func()
obj = A()
obj.cls_func()
# 类方法: 一般就是通过类名去调用的方法,并且自动将类名地址传给cls,
# 但是如果通过对象调用也可以,但是传的地址还是类名地址.
Class method What is the use ???
To give the object can be instantiated class name.
Class attribute can operate.
# 简单引用
# 创建学生类,只要实例化一个对象,写一个类方法,统计一下具体实例化多少个学生?
class Student:
count = 0
def __init__(self,name,id):
self.name = name
self.id = id
Student.addnum()
@classmethod
def addnum(cls):
cls.count = cls.count + 1
@classmethod
def getnum(cls):
return cls.count
obj1 = Student('liye', 12343243243)
obj2 = Student('liye', 12343243243)
obj3 = Student('liye', 12343243243)
obj4 = Student('liye', 12343243243)
obj5 = Student('liye', 12343243243)
obj6 = Student('liye', 12343243243)
print(Student.getnum())
2.2 static method
Decorator @staticmethod
Static method is not dependent on the object and class, in fact, it is a function of the static method
Normative ensure that the code, rational division
Ongoing maintenance of high
For example, I want to define a class about the time of the operation, which has a function of the current time of acquisition.
import time
class TimeTest(object):
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
@staticmethod
def showTime():
return time.strftime("%H:%M:%S", time.localtime())
print(TimeTest.showTime())
t = TimeTest(2, 10, 10)
nowTime = t.showTime()
print(nowTime)
In fact, we can write a similar function to do these things outside of class, but to do so would upset the logical relationship can lead to future code maintenance difficult.
2.3 Properties
What are the characteristics of the property
property is a special property, will be performed for a function (function) that access and returns the value
'''
BMI指数(bmi是计算而来的,但很明显它听起来像是一个属性而非方法,如果我们将其做成一个属性,更便于理解)
成人的BMI数值:
过轻:低于18.5
正常:18.5-23.9
过重:24-27
肥胖:28-32
非常肥胖, 高于32
体质指数(BMI)=体重(kg)÷身高^2(m)
EX:70kg÷(1.75×1.75)=22.86
'''
class People:
def __init__(self,name,weight,height):
self.name=name
self.weight=weight
self.height=height
@property
def bmi(self):
return self.weight / (self.height**2)
p1=People('egon',75,1.85)
print(p1.bmi)
Why use property
After the defined functions into a class characteristics, when obj.name objects used again, can not detect his name is to perform a function and then calculated, use this feature to follow the principle of a unified access
Because the new class has three access methods, we can access several features of their properties, respectively, for the three methods defined on the same property: access, modify, delete
class Foo:
@property
def AAA(self):
print('get的时候运行我啊')
@AAA.setter
def AAA(self,value):
print('set的时候运行我啊')
@AAA.deleter
def AAA(self):
print('delete的时候运行我啊')
#只有在属性AAA定义property后才能定义AAA.setter,AAA.deleter
f1=Foo()
f1.AAA
f1.AAA='aaa'
del f1.AAA
或者:
class Foo:
def get_AAA(self):
print('get的时候运行我啊')
def set_AAA(self,value):
print('set的时候运行我啊')
def delete_AAA(self):
print('delete的时候运行我啊')
AAA=property(get_AAA,set_AAA,delete_AAA) #内置property三个参数与get,set,delete一一对应
f1=Foo()
f1.AAA
f1.AAA='aaa'
del f1.AAA
Commercial examples
class Goods(object):
def __init__(self):
# 原价
self.original_price = 100
# 折扣
self.discount = 0.8
@property
def price(self):
# 实际价格 = 原价 * 折扣
new_price = self.original_price * self.discount
return new_price
@price.setter
def price(self, value):
self.original_price = value
@price.deltter
def price(self, value):
del self.original_price
obj = Goods()
obj.price # 获取商品价格
obj.price = 200 # 修改商品原价
del obj.price # 删除商品原价
3. isinstace 与 issubclass
3.1isinstance
class A:
pass
class B(A):
pass
obj = B()
print(isinstance(obj,B))
print(isinstance(obj,A))
isinstance (a, b): determining whether a class is b (or b derived class) instantiated objects
3.2issubclass
class A:
pass
class B(A):
pass
class C(B):
pass
print(issubclass(B,A))
print(issubclass(C,A))
issubclass (a, b): determining whether a class is a type b (or b derived class) derived classes
Question: So the relationship list str tuple dict, etc. These classes and class Iterable what?
from collections import Iterable
print(isinstance([1,2,3], list)) # True
print(isinstance([1,2,3], Iterable)) # True
print(issubclass(list,Iterable)) # True
# 由上面的例子可得,这些可迭代的数据类型,list str tuple dict等 都是 Iterable的子类。