成员/方法/属性/私有

1.成员
  类里面定义的变量和方法都被称为成员(字段)
  创建对象:
    找类---->开辟空间(__new__)------>__init__()
  变量:
    1.成员变量
    2.类变量
      类名.变量 记住一定要用类名去操作
    可以绑定也可以修改

 1 class StarkConfig(object):
 2     list_display = []
 3     print("类变量的地址:", id(list_display))
 4 
 5     def __init__(self):
 6         self.list_display = []
 7         print(id(self.list_display))
 8 
 9     def get_list_display(self):
10         self.list_display.insert(0, 33)
11         return self.list_display
12 
13 
14 s1 = StarkConfig()
15 s2 = StarkConfig()
16 r1 = s1.get_list_display()
17 print(r1)
18 r2 = s2.get_list_display()
19 print(r2)
20 """
21 类变量的地址: 1885633733192
22 1885633733256
23 1885637388936
24 [33]
25 [33]
26 """
27 
28 class StarkConfig(object):
29     list_display = []
30     print("类变量的地址:", id(list_display))
31 
32     # def __init__(self):
33     #     self.list_display = []
34     #     print(id(self.list_display))
35 
36     def get_list_display(self):
37         self.list_display.insert(0, 33)
38         return self.list_display
39 
40 
41 s1 = StarkConfig()
42 s2 = StarkConfig()
43 r1 = s1.get_list_display()
44 print(r1)
45 r2 = s2.get_list_display()
46 print(r2)
47 """
48 类变量的地址: 2554676732488
49 [33]
50 [33, 33]
51 """
View Code


2.方法:
  1.成员实例方法 加了self的,调用必须用对象去访问
  2.类方法
    当方法需要传递类名的时候.需要类方法。在上方加@classmethod
  3.静态方法 当你的方法不需要传递当前类的对象的时候
    语法规则:在方法上面加@staticmethod
    面试题:静态方法/类方法/实例方法的区别


3.属性:用方法来描述我们的属性信息
    1.@property #表示当前方法是一个属性。方法的返回值就是这个属性的值
    2.这个方法只能有一个参数self
    3.必须有一个返回值

4.私有
  只能在自己类里面访问的
  __方法
  __变量
   __类变量
  都是私有变量,别人访问不到 包括儿子

 1 # 方法属性实例
 2 class Person(object):
 3 
 4     def __init__(self, name, gender, hobby, money):
 5         self.name = name
 6         self.gender = gender
 7         self.hobby = hobby
 8         self.__money = money
 9 
10     def show(self):
11         print("我有" + str(self.__money) + "元钱")
12         # 私有变量在外面不可直接访问
13 
14     @staticmethod
15     def calc(a, b):
16         # 就是一个函数  用不到对象而已
17         return a + b
18 
19     @classmethod
20     def classMethod(cls):
21         # 这里面cls是一个类
22         p = cls("小张", "xx", "chifan", 100)
23         print(type(p), id(p))
24 
25     @property  # 直接当做一个属性来访问 不需要括号
26     def age(self):
27         return 10
28 
29 
30 # 关于调用 既然是类方法和静态方法  那么你当然要用类去调用啊
31 # 实例化一个类:1.找类名  2.__new__   3.__init__()
32 p = Person("test", "不详", "睡觉", 1000000000)
33 p.show()
34 print(p.age)
35 print(Person.calc(2, 3))
36 Person.classMethod()
37 """
38 我有1000000000元钱
39 10
40 5
41 <class '__main__.Person'> 2363753049504
42 """
View Code

猜你喜欢

转载自www.cnblogs.com/gaofeng-d/p/10593010.html