zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python2中为什么在进行类定义时最好要加object

python2 进行 为什么 定义 object 最好
2023-09-14 09:15:51 时间

class Student(object):

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

    def print_score(self):
        print('%s: %s' % (self.name, self.score))
        
lg=Student('lg',99)

lg.name

lg.print_score()

class Person:
    """
    不带object
    """
    name = "zhengtong"


class Animal(object):
    """
    带有object
    """
    name = "chonghong"

if __name__ == "__main__":
    x = Person()
    print ("Person", len(dir(x)))
    print ("Person", dir(x))

    y = Animal()
    print ("Animal", len(dir(y)))
    print ("Animal", dir(y))

lg: 99
Person 27
Person ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
Animal 27
Animal ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

object是一个基类,或称之为元类。在Python3 中加不加一个样