Beta

It's Magic

Description:

Let's Do Magic 🎩


Your task is as simple as coding a class Magic whose objects will get assigned to class attributes.

class Foo:
  a = Magic(10)
  b = Magic(20)

What Can "Magic" Do?

  1. The constructor should take in one parameter which is always of type int

  2. Instances of Magic should define three public properties: whoami, whereami & magic_

    • whoami - returns the name of the class attribute the instance is assigned to

    • whereami - returns the class name in which the instance is in

    • magic_ - a special property as it should be able to handle numbers given with it:

      • Syntax: magic_<number> => magic_10, magic_20, magic_30

      • magic_<number> should return <number> * <number_given_by_constructor>

        • e.g. Magic(5).magic_10 => 50 , Magic(1).magic_100 => 100
  3. It should be impossible to assign new attributes to Magic instances outside of the instance

    • e.g. <class>.<magic_obj>.<attr> = <value> should raise an Error if <attr> would need to be created first
  4. Classes (and hence their instances), which have Magic objects as class attributes, should have a magic property

    • the value of that magic property equals sum(magic_obj.constructor_number for magic_obj in class)

Visualized Task

class Foo:
  a = Magic(5)
  b = Magic(10)
  
  def __init__(self, c):
    self.c = c


print(Foo.a.whoami)    # 'a'
print(Foo.a.whereami)  # 'Foo'

print(Foo.b.whoami)    # 'b'
print(Foo.b.whereami)  # 'Foo'

print(Foo.a.magic_100) # 500
print(Foo.b.magic_6)   # 60

# Assignmnets like this should be prohibited 
Foo.a.any_non_existing_attr = 10 # ERROR
Foo.b.any_non_existing_attr = 5  # ERROR

foo_obj = Foo(8)

print(foo_obj.magic) # 15  <=  Foo.a.number + Foo.b.number + ... 
print(foo_obj.c)     # 8

Note: The import of the inspect package is prohibited


Happy coding!

Metaprogramming

More By Author:

Check out these other kata created by chr3st5an

Stats:

CreatedJul 15, 2022
PublishedJul 15, 2022
Warriors Trained98
Total Skips36
Total Code Submissions70
Total Times Completed18
Python Completions18
Total Stars7
% of votes with a positive feedback rating95% of 11
Total "Very Satisfied" Votes10
Total "Somewhat Satisfied" Votes1
Total "Not Satisfied" Votes0
Total Rank Assessments10
Average Assessed Rank
5 kyu
Highest Assessed Rank
4 kyu
Lowest Assessed Rank
6 kyu
Ad
Contributors
  • chr3st5an Avatar
Ad