Python 学习笔记

1. 字典转点属性

class dict_dot_notation(dict):
    """ 这是将字典转换为点表示法的类 """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__dict__ = self

if __name__ == '__main__':
    d = dict_dot_notation({'a': 1, 'b': 2})
    print(d.a)
    print(d.b)
    d.c = 3
    print(d.c)

2. 类中 __dict__ 的应用

Python 类提供了 __dict__ 属性,该属性可以用类名或者类的实例对象来调用,用类名直接调用 __dict__,会输出该由类中所有类属性组成的字典;而使用类的实例对象调用 __dict__,会输出由类中所有实例属性组成的字典。

class CLanguage:
    a = 1
    b = 2
    def __init__ (self):
        self.name = "C语言中文网"
        self.add = "http://c.biancheng.net"
#通过类名调用__dict__
print(CLanguage.__dict__)
# 结果为:
# {'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function CLanguage.__init__ at 0x0000022C69833E18>, '__dict__': <attribute '__dict__' of 'CLanguage' objects>, '__weakref__': <attribute '__weakref__' of 'CLanguage' objects>, '__doc__': None}

#通过类实例对象调用 __dict__
clangs = CLanguage()
print(clangs.__dict__)
# 结果为:
# {'name': 'C语言中文网', 'add': 'http://c.biancheng.net'}

通过这一属性可以实现一下功能:

class Color:
    green = (0, 128, 0)
    white = (255, 255, 255)
		...
    @staticmethod
    def random(obj_id: int) -> Tuple[int, int, int]:
        color_list = [
            c
            for c in Color.__dict__.keys()
            if c[:2] != "__"
            and c not in ("random", "red", "white", "grey", "black", "silver")
        ]
        return getattr(Color, color_list[obj_id % len(color_list)])

3. 嵌套类(内类)

嵌套类(也叫内类)是在另一个类中定义的。它在所有面向对象的编程语言中都是非常常用的,可以有很多好处。它并不能提高执行时间,但可以通过将相关的类归为一组来帮助程序的可读性和维护,而且还可以将嵌套类隐藏起来,不让外界看到。

下面的代码展示了一个非常简单的嵌套类的结构。

class Dept:
    def __init__(self, dname):
        self.dname = dname
    class Prof:
        def __init__(self,pname):
            self.pname = pname

math = Dept("Mathematics")
mathprof = Dept.Prof("Mark")

print(math.dname)
print(mathprof.pname)

输出

Mathematics
Mark

注意,我们不能直接访问内部类。我们使用 outer.inner 格式创建其对象。

我们可以访问外类中的嵌套类,但不能反过来访问。要访问外类中的嵌套类,我们可以使用 outer.inner 格式或 self 关键字。

在下面的代码中,我们对上述类做了一些改动,并使用父类访问嵌套类的一个函数。

class Dept:
    def __init__(self, dname):
        self.dname = dname
        self.inner = self.Prof()
    def outer_disp(self):
        self.inner.inner_disp(self.dname)
    class Prof:
        def inner_disp(self,details):
            print(details, "From Inner Class")

math = Dept("Mathematics")

math.outer_disp()

输出

Mathematics From Inner Class