gpt4 book ai didi

python - 类的用法&&继承: am I doing wrong?

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:50 24 4
gpt4 key购买 nike

我刚刚开始在 Python 2.7 中尝试 OOP。

这是我目前为我的项目编写的代码示例。这只是"template" - 不是应用程序的真实代码,但此应用程序将使用相同的类“方案”,如下例所示。

我想知道 - 我在这里做错了什么?类初始化,一些错误的继承用法,还有其他错误吗?

它有效,但是 - 也许我的一些“意识形态”观点是错误的?

文件:main.py - 程序主体; cl1.py - 第一类; cl2.py - 第二类。

main.py:

#!/usr/bin/env python

import cl1, cl2

print('\nStarted Main script.\n')

cl1 = cl1.First()
cl1.one('This is first_arg')

cl2 = cl2.Second()
cl2.two('This is second arg')

cl1.py:

class First:

def one(self, first_arg):

self.third_arg = 'This is third arg from First class'

self.first_arg = first_arg
print('This is method \'one\' from class First.\nWork with first_arg = %s\n' % self.first_arg)

cl2.py:

from cl1 import First

class Second(First):

def two(self, second_arg):

self.second_arg = second_arg
print('This is method \'two\' from class Second.\nWork with second_arg = %s\n' % self.second_arg)

self.one('I came from Second.two() to First.one()')

print('I came from First.one() as self.third_arg to Second.two(): %s\n' % self.third_arg)

结果:

$ ./main.py

Started Main script.

This is method 'one' from class First.
Work with first_arg = This is first_arg

This is method 'two' from class Second.
Work with second_arg = This is second arg

This is method 'one' from class First.
Work with first_arg = I came from Second.two() to First.one()

I came from First.one() as self.third_arg to Second.two(): This is third arg from First class

最佳答案

您不应该在类的方法中即时创建类的属性。类应该知道在初始化时它从父类(super class)继承了哪些属性。您应该仅在 __init__ 中创建实例变量,一个特殊的构造方法。

class First(object):
def __init__(self, first_arg):
self.first_arg = first_arg

@property
def one(self):
return self.first_arg

@one.setter
def one(self, value):
self.first_arg = value
<小时/>
>>> first = First(5)
>>> print first.one
5
>>> first.one = 10
>>> print first.one
10
<小时/>

如果您想通过创建名为 Second 的新类来向 First 类添加额外属性,则应始终首先在子类的构造函数中继承父类(super class)的属性:

class Second(First):
def __init__(self, first_arg, second_arg):
super(Second, self).__init__(first_arg) # now you have "self.first_arg"
self.second_arg = second_arg

@property
def two(self):
return self.second_arg

@two.setter
def two(self, value):
self.second_arg = value
<小时/>
>>> second = Second(7, 10)
>>> print second.one
7
>>> print second.two
10
>>> second.two = 20
>>> second.one = 15
...

希望这有帮助。

关于python - 类的用法&&继承: am I doing wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28643982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com