[英]Python initializing attributes of objcts
如果有以下問題:我需要在 Python 中編寫一個名為 filament 的類。 對象細絲具有屬性head
,還需要具有其他兩個屬性up
和down
。 這就是我所做的:
class filament(object):
def __init__(self, start):
self.head = start
head.up = 1
head.down = 1
fil = filament(1)
如果我運行它,我會得到: "NameError: name 'head' is not defined"
。
先感謝您!
根據你的問題
您需要對象細絲具有屬性頭,還需要具有其他兩個屬性,“向上”和“向下”。
為此,您可以創建一個具有屬性up
和down
。 即,像這樣的東西。
class Head(object):
def __init__(self, *args):
self.up, self.down = args
class filament(object):
def __init__(self, start):
self.head = Head(1, 1)
fil = filament()
print(fil.head.up)
print(fil.head.down)
您還可以使用collections
模塊中的namedtuple
來獲得相同的行為。
from collections import namedtuple
Head = namedtuple('Head', ['up', 'down'])
class filament(object):
def __init__(self):
self.head = Head(1, 1)
fil = filament()
print(fil.head.up)
print(fil.head.down)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.