[英]'>=' not supported between instances of 'NoneType' and 'float'
[英]'>' not supported between instances of 'float' and 'NoneType'
我運行以下代碼來定義一些基本對象:
import logging
class State:
"""A class representing a US state."""
def __init__(self, name, postalCode, population):
self.name = name
self.postalCode = postalCode
self.population = population
def __str__(self):
"""Readable version of the State object"""
return 'Name: ' + self.name + ", Population (in MM): " + str(self.population) + ", PostalCode: " + self.postalCode
def increase_population(self, numPeople):
"""Increases the population of the state."""
self.population += numPeople
print("Population of",self.name,"increased to",self.population,"million.")
def decrease_population(self, numPeople):
"""Decreases the population of the state."""
try:
if (numPeople > self.population):
raise ValueError("decrease_population(self, numPeople): Invalid value for population reduction")
else:
# decrease the population by the value in variable numPeople
self.population -= numPeople
# Print new population
print("Population of",self.name,"decreased to",self.population,"million.")
except Exception as e:
logging.exception(e)
# Test Cases
# Create an instance of State 'il' corresponding to Illinois, with a postal code of IL and a population of 12.8 million
il = State("Illinois","IL",12.8)
# use the given method to increase the population of il by 1 million
il.population = State.increase_population(il, 1)
# use the given method to decrease the population of il by 1.5 million
il.population = State.decrease_population(il, 1.5)
但是我收到一個 TypeError: '>' not supported between 'float' and 'NoneType'錯誤在線
if (numPeople > self.population):
我試圖在 SO 上找到解決方案,但沒有找到有效的答案。
看起來您正在混合實例方法,即自我和靜態/類方法。
將您的代碼更改為
il = State("Illinois", "IL", 12.8)
# use the given method to increase the population of il by 1 million
il.increase_population(1)
# use the given method to decrease the population of il by 1.5 million
il.decrease_population(1.5)
實例方法increase_population
返回 None 這使得
il.population = State.increase_population(il, 1
)
到 None 另外increase_population(il, 1)
是實例方法,當您將實例名稱傳遞給它並像 static_method 一樣調用時,可以像il.increase_population(1)
一樣調用它
與方法decrease_population
相同的解釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.