如何在Python中创建打印方法

时间:2015-06-25 15:53:30

标签: python class object printing

我对python很新,并且在c ++中有一点背景。我只是想到了面向对象的编程,但是我在创建这个类中定义打印方法时遇到了问题。我已经阅读了repr()和str()函数,但它们似乎都不起作用。

[ldap]
        server = ldap://xxx.OurDomain.com
        username = CN=ldapread,DC=OurDomain,DC=com
        password = NotShownHere
        accountBase = DC=OurDomain,DC=com
        groupBase = DC=OurDomain,DC=com

任何人都可以解释我如何创建一个方法,这样我就可以简单地打印有关该对象的信息(即peep.print_species =“Gallus Domesticus”)?

由于

3 个答案:

答案 0 :(得分:0)

您在函数调用结束时缺少括号。

<input type="text" 
             class="form-control" 
             datepicker-popup="fullDate" 
             ng-model="dt" 
             is-open="opened"
             datepicker-options="dateOptions"
             ng-required="true" 
             close-text="Close" />

当您编写没有括号的peep.print_eatable() peep.print_species() 时,Python不会报告语法错误,因为它是一个完全合法的语句,它返回方法对象peep.print_species

答案 1 :(得分:0)

您需要 CALL 您的方法,而不仅仅是获取它们。将print_species放在你的陈述后面:

()

答案 2 :(得分:0)

您需要在函数调用结束时添加括号:

peep.print_eatable()
peep.print_species()

所以代码应该是:

class chicken():
    def __init__(self, name, eatable, species):
        self.name=name
        if eatable!="yes" and eatable!="no":
            self.eatable="no"
        else:
            self.eatable=eatable
        self.species=species
    #Print the species when called
    #Doesnt work for some reason
    def print_species(self):
        print"%s" %str(self.species)
    #Print whether or not the bird is eatable
    #This method also doesnt work
    def print_eatable(self):
        print "%s" %str(self.eatable)
    def change_species(self, new_name):
        self.species=new_name
    def change_eatable(self, new_status):
        self.eatable=new_status
        if new_status!="yes" and new_status!="no":
            self.eatable="no"
        else:
            self.eatable=new_status
peep=chicken("Peep", "yes", "Gallus Domesticus")
peep.change_eatable("meatballs")
peep.print_eatable()
peep.print_species()
#This does work
print peep.eatable