Python Class

暂时先贴一篇代码:

class MyClass:
    i=123;
    def f(self):
        return 'HelloWorld'
print(MyClass.i)
#print(MyClass.f())#这样使用是非法的
xxx=MyClass();
print(MyClass.f(xxx))#这样才是合法的,或者用后面写的那种
xx=MyClass();
print(xx.f())
#类中的__init__函数能够自动为类进行初始化
class Complex:
    def __init__(self,realpart,imagpart):
        self.r=realpart
        self.i=imagpart
x=Complex(3.0,-4.5)
print(x.r,x.i)
##############################
#下面讲一下类的继承
class Fruit():
    def color(self):
        print("colorful")
class Apple(Fruit):
    pass
class Orange(Fruit):
    pass
apple=Apple()
orange=Orange()
apple.color()
orange.color()
#子类除了可以继承父类的方法,还可以覆盖父类:
class iFruit():
    def color(self):
        print("colorful")

class iApple(Fruit):
    def color(self):
        print("red")

class iOrange(Fruit):
    def color(self):
        print("orange")

iapple = iApple()
iorange = iOrange()
iapple.color()
iorange.color()
#子类可以在继承父类方法的同时,对方法进行重构。这样一来,子类的方法既包含父类方法的特性,同时也包含子类自己的特性:
class aFruit():
    def color(self):
        print("Fruits are colorful")

class aApple(Fruit):
    def color(self):
        super().color()
        print("Apple is red")

class aOrange(Fruit):
    def color(self):
        super().color()
        print("Orange is orange")

aapple = aApple()
aorange = aOrange()
aapple.color()
aorange.color()

# 输出
# Fruits are colorful
# Apple is red
# Fruits are colorful
# Orange is orange
posted @ 2021-11-11 20:26  Mudrobot  阅读(38)  评论(0编辑  收藏  举报