day16,成员(类,对象)

一,成员:

  变量:

    1,实例变量,对象 . xxx = xxx 实例变量 --》字段 --》属性,给对象用的。

    

class Person:
    def __init__(self, name, card_no, height, weight, address):
          # 实例变量. 给对象赋值
         self.name = name
         self.card_no = card_no
         self.height = height
         self.weight = weight
         self.address = address
p1 = Person("老马", "1234", 1.60, 180, "深圳市南山区南")
p1.company = "腾讯" # 添加实例变量-> 字段 -> 属性(java)

    2,类变量,直接写在类中的变量就是类变量,类变量一般用类名来访问

class Person:
    country = "中国"
    def __init__(self,name, age):
        self.name = name
        self.age = age

Person.country = "大清"  # 类变量
print(Person.country) # 直接使用类名进行访问

二,方法:

    1,实例方法,对象 . 方法()

class Car:
    def run(self):
        print("会跑的车")

    def cul(self, a, b):
        return a + b

    def jump(self):
        print("you jump i jump")

c = Car()
c.run() # 调用实例方法
print(c.cul(1 , 3))
c.jump()

    2,类方法,    类名 . 方法()

class Person:

    def chi(self): # 实例方法
        print("人在吃")

    # 类方法
    @classmethod # 类方法
    def he(cls): # cls 类
        print(cls)
        print("我是喝")

    @staticmethod
    def shui():  # 在类中定义的一个普通函数
        print("和你睡不等于睡你 -- 姜文")

    @staticmethod
    def 上天(height):  # 在类中定义的一个普通函数
        print("上天%s" % height)


# print(Person)
# Person.he()

# p = Person()
# p.he() # 不管用对象还是用类去访问类方法. 默认传递进去的是类

Person.shui()
Person.上天(500)
#
# p = Person()
# p.shui()

    3,静态方法,类名 . 方法()

三,属性 @property

    把方法转化成属性。

    对象 . 属性

class Person:
    def __init__(self, name): # 构造, 创建对象的时候自动调用
        self.__name = name # 私有的
        print("这里是构造方法")

    def init(self):
        print("实例方法")

    def __chi(self): # 私有的
        print("我要吃. 疯狂的吃")

    def he(self):
        self.__chi() # 内部调用
        print("我是喝", self.__name)

p = Person("孙艺珍")
p.he()
# p.init()
# print(p.__name)

四,私有:

    __做为前缀

    只能在自己类中随意访问,但是除了类就无法访问到这个私有内容。

  

原文地址:https://www.cnblogs.com/wm828/p/9937287.html