Python面向对象-类

一、创建类以及类变量

class Person:
    name = "xiaofeng"  # 类变量

    # 定义方法
    def say_hello(self):
        print(f"hello {Person.name}")


if __name__ == '__main__':
    # 1.访问类变量
    print(Person.name)
    # 2.访问类中定义的方法
    # 实例化类
    p = Person()
    p.say_hello()

二、使用构造器创建实例变量

class Person:
    # 构造器,创建类的时候会自动调用这个方法
    def __init__(self, name, age):
        self.username = name  # 实例变量
        self.age = age
        self.email = f"{name}@163.com"

    def say_hello(self):
        print(f"hello {self.username},age:{self.age},email:{self.email}")


if __name__ == '__main__':
    p1 = Person("xiaofeng", 22)
    p1.say_hello()

    p2 = Person("xiaolong", 22)
    p2.say_hello()

三、类变量与实例变量的区别

class Employee:
    up = 0.1

    # 构造器,创建类的时候会自动调用这个方法
    def __init__(self, name, salary):
        self.username = name  # 实例变量
        self.salary = salary

    def up_salary(self):
        self.salary = self.salary * (1 + self.up)


if __name__ == '__main__':
    # Employee.up = 0.2 # 修改类变量
    p1 = Employee("xiaofeng", 20000)
    p1.up = 0.2
    p1.up_salary()
    print("xiaofeng:", p1.salary)
    p2 = Employee("xiaolong", 10000)
    p2.up_salary()
    print("xiaolong:", p2.salary)

四、类的继承

class Animal:

    def __init__(self, name, legs):
        self.name = name
        self.legs = legs

    def info(self):
        print(f"name:{self.name},legs:{self.legs}")


# 子类继承父类
class Dog(Animal):
    # 方法重写,会把父类中的方法覆盖
    def info(self, others):
        print(f"name:{self.name},leg:{self.legs},{others}")


# 子类继承父类
class Cat(Animal):
    # 在子类中增加方法
    def walk(self):
        print(f"{self.name}用{self.legs}条走路")


if __name__ == '__main__':
    d = Dog("贝拉", 4)
    d.info("wangwang")

    c = Cat("梨花", 4)
    c.info()
    c.walk()

五、类的私有属性和私有方法

class Animal:

    def __init__(self, name, legs):
        self.name = name
        self.legs = legs
        self.__age = 10  # 变量前加两个下划线,表示私有变量,该变量不能被继承,只能在自己类的内部使用

    def info(self):
        print(f"name:{self.name},legs:{self.legs},age:{self.__age}")
        self.__private_info() # 在类的内部访问私有方法

    # 私有方法,只能在类的内部访问,无法继承,无法在外部访问
    def __private_info(self):
        print(f"private_info")


# 子类继承父类
class Dog(Animal):
    # 方法重写,会把父类中的方法覆盖
    def info(self, others):
        # 私有属性在子类中是访问不到的
        print(f"name:{self.name},leg:{self.legs},{others}")


# 子类继承父类
class Cat(Animal):
    # 在子类中增加方法
    def walk(self):
        print(f"{self.name}用{self.legs}条走路")


if __name__ == '__main__':
    # d = Dog("贝拉", 4)
    # print(d.info("wangwang"))

    c = Cat("梨花", 4)
    c.info()

六、类的属性方法

class Person:
    def __init__(self, name):
        self.__name = name

    @property  # 像访问属性一样去访问方法
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        self.__name = value


if __name__ == '__main__':
    p1 = Person("xiaofeng")
    p1.name = "xiaolong"
    print(p1.name)

你可能感兴趣的:(Python开发,python,开发语言)