(有C/C++基础)Python 学习:基础知识点 第六节

创建类,创建对象,实例方法(非静态)、实例属性(非静态)

class Test(object):
    def Init(self):
        self.a = 10
	
    def Print(self):
        print('hello class', self.a)


t = Test()
t.Init()
t.Print()
print(t.a)

类属性(静态成员变量)、静态方法(静态成员函数)、类方法
静态方法和C++的静态成员函数不能完全等价,类方法才可以

class Test(object):
    a = 100

    def Print1(self):
        print('hello world')

    Print1 = staticmethod(Print1)

    @staticmethod  # 函数修饰符,也叫装饰器,对于静态方法,不需要self这样的参数
    def Print2():
        print('hello world')

    @classmethod
    def Print3(cls):
        print(cls.a)


print(Test.a)
print(Test.Print())

Python中使用双下划线前缀( __ )来表示私有成员

class Test(object):
    def __init__(self):
        self.__x = 10  # 私有成员外部不能直接访问

继承
如果一个类没有从任何一个父类继承, 那么可以让这个类继承自object
如果子类中存在和父类中相同名字的方法, 子类方法会覆盖父类方法
这一点在实现类的构造器要额外注意. 子类和父类都有同名的构造器. 子类的构造器中需要显式调用父类构造器

class Parent(object):
    def __init__(self):
        self.x = 10

    def ParentPrint(self):
        print('parentmethod', self.x)


class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
        self.y = 20

    def ChildPrint(self):
        print('childparent', self.x, self.y)


p = Parent()
c = Child()

p.ParentPrint()
c.ChildPrint()
c.ParentPrint()
发布了146 篇原创文章 · 获赞 82 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_40860852/article/details/102573602