简体   繁体   中英

Using class variables in methods of the same class in Python

I am currently learning Python at home using the Python for Dummies all in one book. I'm on the chapter about classes and in particular the section on class variables. So far, the code has been running fine, but yesterday I got stuck for about two hours trying to get my code to work and I'm not sure why it doesn't work the way I expect. My code is this:

class Crew_Member:
    """A class for creating an individual record"""
    is_human = True

    def __init__(self, full_name, username, rank="crewmember"):
        self.full_name = full_name
        self.username = username
        self.rank = rank
        self.join_date = dt.date.today()

    def file_age(self):
        return f"{self.full_name}'s file was created on {self.join_date:%d/%m/%y}"

    def promote(self, rank):
        self.rank = rank

    def not_human(self):
        if Crew_Member.is_human:
            self.rank = "Mech/Scutter"

So my understanding is that is_human is the class variable. The method I'm trying to use it in is not_human . The idea is that each object would be the personel record for a crew member. If that crew member is not human, they automatically get the rank of "Mech/Scutter".

The way I imagined it working is after the object has been called, you change that instance's value of is_human to false, run the method not_human , and that would change their rank accordingly. The first time I tried and got the correct rank, the class variable hadn't changed:

第一次尝试

My code (as written above) works fine, but this is what I have to enter to get it to work:

最终代码

So this is my problem: The for loop in the not_human method says "If class variable is true, then change rank". But the class variable has been changed to false (as ilustrated by the first print line) so why does it work?

But the class variable has been changed to false...

No, the line BobScutt.is_human = False turns it into an instance variable. The class variable remains untouched. If you want to change it, you have to manipulate the Crew_Member class directly, not one of its instances.

Observe:

class TestClass:
    test_attr = True
    
foo = TestClass()
foo.test_attr = False

print("Test attribute in foo:", foo.test_attr)
print("Test attribute in TestClass:", TestClass.test_attr)

Output:

Test attribute in foo: False
Test attribute in TestClass: True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM