私が持ってPerson
保持しているクラス、age
今私は、すべてのメソッドの内部の中にそれがアクセスできるようにする必要があり、財産をPerson
すべてのメソッドが正しく動作するように、クラス
私のコードは次のとおりです。
class Person:
#age = 0
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
if(initialAge < 0):
print("Age is not valid, setting age to 0.")
age = 0
age = initialAge
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
if(age < 13):
print("You are young.")
elif(age>=13 and age<18):
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
Person.age += 1 # I am having trouble with this method
t = int(input())
for i in range(0, t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(0, 3):
p.yearPasses()
p.amIOld()
print("")
yearPasses()
はage
1増加するはずですが、呼び出されても何も実行されません
それを機能させるためにどのように適応させるのですか?
age
Personクラスのインスタンス属性である必要があります。これを行うには、次のself.age
ような構文を使用します。
class Person:
def __init__(self, initialAge):
# Add some more code to run some checks on initialAge
if initialAge < 0:
print("Age is not valid, setting age to 0.")
self.age = 0
self.age = initialAge
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
if self.age < 13:
print("You are young.")
elif 13 <= self.age <= 19:
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
self.age += 1
#test
age = 12
p = Person(age)
for j in range(9):
print(j, p.age)
p.amIOld()
p.yearPasses()
出力
0 12
You are young.
1 13
You are a teenager.
2 14
You are a teenager.
3 15
You are a teenager.
4 16
You are a teenager.
5 17
You are a teenager.
6 18
You are a teenager.
7 19
You are a teenager.
8 20
You are old.
元のコードには次のようなステートメントがありました
age = initialAge
その方法で。これage
は、メソッドで指定されたローカルオブジェクトを作成するだけです。このようなオブジェクトはメソッドの外部には存在せず、メソッドの終了時にクリーンアップされるため、次にメソッドを呼び出すときに、その古い値はage
失われます。
self.age
クラスインスタンスの属性です。クラスのどのメソッドもself.age
構文を使用してその属性にアクセスして変更でき、クラスの各インスタンスには独自の属性があるため、Personクラスの複数のインスタンスを作成すると、それぞれに独自のがあり.age
ます。
クラス自体の属性であるオブジェクトを作成することも可能です。これにより、クラスのすべてのインスタンスが単一のオブジェクトを共有できるようになります。例えば、
Person.count = 0
.count
Personクラスという名前のクラス属性を作成します。メソッドの外部に代入ステートメントを配置して、クラス属性を作成することもできます。例えば、
class Person:
count = 0
def __init__(self, initialAge):
Person.count += 1
# Add some more code to run some checks on initialAge
#Etc
プログラムがこれまでに作成したPersonインスタンスの数を追跡します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加