在这里,我想将一个类对象属性发送到其他 class.my 基本程序
如下所示class A():
def __init__(self,name,age):
Self.name = name
Self .age = age
Return tuple(self.name,self.age)
Class B():
def __init__(self,oldInfo,job):
Self.oldInfo=oldInfo
Self.job=job
Name,age= oldInfo
Print(Name,age,job)
#calling block
Obj1=A("Scott","28")
Obj2=B(Obj1,"devolper")
所以发生了一些错误,例如
过度开箱
应该返回 无 不是元组
返回值应为 1 个值而不是多个值
- 组应该是
tuple((self.name,self.age))
而不是tuple(self.name,self.age)
,因为tuple()
只接收1个参数而不是2个参数。我不确定在 python3 上( __init__()
应该返回 None 而不是元组,因为它会创建一个对象,请尝试弄清楚它。- 结果,
oldInfo
是"一个"对象,并且您尝试将其解压缩为2,名称和年龄,因此您收到"过度解包"错误。
__init__()
方法必须始终返回 None。你不能让它返回任何其他东西。您可以将元组粘贴到实例变量中,然后在实例上使用 getter 方法或(不太 python(直接获取元组。您也不正确地使用了tuple()
。tuple()
将单个参数作为元组或列表,而不是两个单独的参数。调用tuple()
也不一定,因为您只需执行foo = ('something', 'something else')
即可创建新元组
class A():
def __init__(self, name, age):
self.name = name
self.age = age
self.tuple = (self.name, self.age)
class B():
def __init__(self, oldInfo, job):
self.oldInfo = oldInfo
self.job = job
name, age = oldInfo.tuple
print(name, age, job)
obj1 = A("Scott", "28")
obj2 = B(obj1, "developer")
另请注意,元组并不是真正必需的,因为您已经在 A 类中分配了名称和年龄作为属性。你可以从 B 调用它们,因为 B 已经有对整个对象的引用:
class A():
def __init__(self, name, age):
self.name = name
self.age = age
class B():
def __init__(self, oldInfo, job):
self.oldInfo = oldInfo
self.job = job
print(oldInfo.name, oldInfo.age, job)
obj1 = A("Scott", "28")
obj2 = B(obj1, "developer")
所以当我回答这个问题时,我想我应该给你一些建议。
1、python关键字首字母为小写,def不是Def.others也是。 您可以查看我的代码或在空闲时使用此代码。
import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import',
'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
2、另一种是你应该在代码中使用缩进的四个空格。
3、当你想要获取属性时,你应该在代码中定义方法.theObj1=A("Scott","28"(,Obj1只是一个类为A的对象,你可以用方法使用对象来获取你的属性。
我的代码:
class A():
def __init__(self,name,age):
self.name = name
self .age = age
def gettuple(self):
return tuple([self.name,self.age])
class B():
def __init__(self,oldInfo,job):
self.oldInfo = oldInfo
self.job = job
(Name,age) = oldInfo
print(Name,age,job)
#calling block
devolper = 'goggo'
Obj1=A("Scott","28")
Obj2=B(Obj1.gettuple(),devolper)
上次,我认为您应该在 python.org 中了解更多示例,在此处输入链接描述