我想确定变量 1 是男性还是女性。我想使用从条件调用的类(如您在我的代码中所见)
我得到错误:
if variable1 == gender.male:
AttributeError: 'Gender' object has no attribute 'male'
但我可能拼错了课程。我对课程不是很有经验。我需要该类成为具有 male.startswith("o") 和 female.startswith("a") 的语法规则容器。接下来我用条件调用类的规则,以检查 variable1 是 gender.male 还是 gender.female。我需要调用条件,所以 if variable1 == gender.male(或类似的)
你能告诉我如何从我的代码示例中获得
"Pedro is male"
输出吗? (或者 "Lola is Female"
以防我用 Lola 更改 variable1 的内容)。谢谢
variable1 = "Pedro"
class Gender:
def __eq__(self, male, female):
x= male.startswith("o")
y= female.startswith("a")
return x,y
gender = Gender()
if variable1 == gender.male:
print(variable1, " is male")
else:
print(variable1, " is female")
您可以创建一个具有
person object
和name
作为他们的gender
的class variables
。然后,您可以创建一个函数来确定性别,前提是提供一个名称作为输入:
def identify_gender(name):
if name.lower().endswith('o'):
return "Male"
elif name.lower().endswith('a'):
return "Female"
else:
return "Undefined"
class Person:
def __init__(self, name):
self.name = name
self.gender = identify_gender(self.name)
variable1 = "Pedro"
person_obj = Person(variable1)
print("{} is a {}".format(person_obj.name, person_obj.gender))
控制台输出:
Pedro is a Male
注意
lower()
在所有字母大写的情况下更通用。
课堂上识别单词性别的问题。 AttributeError:“性别”对象没有属性“男性”
我相信这个错误是不言自明的:你的“性别”对象(特别是你的实例“性别”)没有男性属性。
我想确定一个字符串是男性还是女性。
从您的示例中,您似乎知道如何使用 if 语句来确定字符串是 masculine 还是 feminine 但是我认为您应该使用
endswith
函数而不是 startswith
来检测此属性通过将字符串的最后一个字符与自定义值进行比较:
variable1 = "Pedro"
if variable1.endswith("o"):
print(variable1, "is male")
elif variable1.endswith("a"):
print(variable1, "is female")
我想使用从条件调用的类。但我可能拼错了班级。我对课程不是很有经验。
你没有拼错类,而是发生了另外两件事:
__eq__
方法,此方法用于比较实例但在您的代码中您只使用一个实例gender
。要在不比较实例的情况下初始化类属性(每个实例都是 unique),您应该使用 __init__
方法。x = value
而不是您需要使用关键字 self
引用当前实例,如 self.x = value
。另外,请注意,您不需要从内部函数返回值init
.class Gender:
def __init__(self, variable):
self.male = variable.endswith("o")
self.female = variable.endswith("a")
你能告诉我如何从我的代码示例中获得“Pedro is male”输出吗? (或者“Lola is Female”,以防我用 Lola 更改 variable1 的内容)。谢谢
variable1 = "Pedro"
class Gender:
def __init__(self, variable):
self.male = variable.endswith("o")
self.female = variable.endswith("a")
gender = Gender(variable1)
if gender.male:
print(variable1, "is male")
elif gender.female:
print(variable1, "is female")
然而,根据我的经验,这将是一种更面向对象的使用 classes 和思考问题的方式:
class Person:
def __init__(self, name):
self.name = name
self.male = name.endswith("o")
self.female = name.endswith("a")
def printPersonGender(self):
if self.male:
print(self.name, "is male")
elif self.female:
print(self.name, "is female")
else:
print(self.name, "is unknown")
firstPerson = Person("Pedro")
firstPerson.printPersonGender()
secondPerson = Person("Lola")
secondPerson.printPersonGender()